谁有人和兽做的网站/整站优化外包服务

谁有人和兽做的网站,整站优化外包服务,上海全上海全国网站建设,WordPress分类ID能修改吗Scrapy框架简介 Scrapy是:由Python语言开发的一个快速、高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据,只需要实现少量的代码,就能够快速的抓取。 新建项目 (scrapy startproject xxx):新建一个新的…

Scrapy框架简介

image-20250320114955165

Scrapy是:由Python语言开发的一个快速、高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据,只需要实现少量的代码,就能够快速的抓取。

  1. 新建项目 (scrapy startproject xxx):新建一个新的爬虫项目
  2. 明确目标 (编写items.py):明确你想要抓取的目标
  3. 制作爬虫 (spiders/xxspider.py):制作爬虫开始爬取网页
  4. 存储内容 (pipelines.py):设计管道存储爬取内容

注意!只有当调度器中不存在任何request了,整个程序才会停止,(也就是说,对于下载失败的URL,Scrapy也会重新下载。)

本篇文章不会讲基本项目创建,创建的话可以移步这个文章,基础的肯定没什么重要性,这篇说明一下一些比较细的知识

Scrapy 官网:https://scrapy.org/
Scrapy 文档:https://docs.scrapy.org/en/latest/
GitHub:https://github.com/scrapy/scrapy/

基本结构

image-20250319221256508

image-20250319203420077

定义爬取的数据结构

  1. 首先在items中定义一个需要爬取的数据结构

    class ScrapySpiderItem(scrapy.Item):# 创建一个类来定义爬取的数据结构name = scrapy.Field()title = scrapy.Field()url = scrapy.Field()
    

    那为什么要这样定义:

    在Scrapy框架中,scrapy.Field() 是用于定义Item字段的特殊类,它的作用相当于一个标记。具体来说:

    1. 数据结构声明
      每个Field实例代表Item中的一个数据字段(如你代码中的name/title/url),用于声明爬虫要收集哪些数据字段。
    2. 元数据容器
      虽然看起来像普通赋值,但实际可以通过Field()传递元数据参数:

    在这里定义变量之后,后续就可以这样进行使用

    item = ScrapySpiderItem()
    item['name'] = '股票名称'
    item['title'] = '股价数据'
    item['url'] = 'http://example.com'
    

    然后就可以输入scrapy genspider itcast "itcast.cn"命令来创建一个爬虫,爬取itcast.cn域里的代码

数据爬取

注意这里如果你是跟着菜鸟教程来的,一定要改为这样,在itcast.py中

import scrapyclass ItcastSpider(scrapy.Spider):name = "itcast"allowed_domains = ["iscast.cn"]start_urls = ["http://www.itcast.cn/channel/teacher.shtml"]def parse(self, response):filename = "teacher.html"open(filename, 'wb').write(response.body)

改为wb,因为返回的是byte数据,如果用w不能正常返回值

那么基本的框架就是这样:

from mySpider.items import ItcastItemdef parse(self, response):#open("teacher.html","wb").write(response.body).close()# 存放老师信息的集合items = []for each in response.xpath("//div[@class='li_txt']"):# 将我们得到的数据封装到一个 `ItcastItem` 对象item = ItcastItem()#extract()方法返回的都是unicode字符串name = each.xpath("h3/text()").extract()title = each.xpath("h4/text()").extract()info = each.xpath("p/text()").extract()#xpath返回的是包含一个元素的列表item['name'] = name[0]item['title'] = title[0]item['info'] = info[0]items.append(item)# 直接返回最后数据return items

爬取信息后,使用xpath提取信息,返回值转化为unicode编码后储存到声明好的变量中,返回

数据保存

主要有四种格式

  1. scrapy crawl itcast -o teachers.json
  2. scrapy crawl itcast -o teachers.jsonl //json lines格式
  3. scrapy crawl itcast -o teachers.csv
  4. scrapy crawl itcast -o teachers.xml

不过上面只是一些项目的搭建和基本使用,我们通过爬虫渐渐进入框架,一定也好奇这个框架的优点在哪里,有什么特别的作用

scrapy结构

pipelines(管道)

这个文件也就是我们说的管道,当Item在Spider中被收集之后,它将会被传递到Item Pipeline(管道),这些Item Pipeline组件按定义的顺序处理Item。每个Item Pipeline都是实现了简单方法的Python类,比如决定此Item是丢弃而存储。以下是item pipeline的一些典型应用:

  • 验证爬取的数据(检查item包含某些字段,比如说name字段)
  • 查重(并丢弃)
  • 将爬取结果保存到文件或者数据库中
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html# useful for handling different item types with a single interface
from itemadapter import ItemAdapterclass MyspiderPipeline:def process_item(self, item, spider):return item

settings(设置)

代码里给了注释,一些基本的设置

# Scrapy settings for mySpider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#项目名称
BOT_NAME = "mySpider"SPIDER_MODULES = ["mySpider.spiders"]
NEWSPIDER_MODULE = "mySpider.spiders"# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = "mySpider (+http://www.yourdomain.com)"
#是否遵守规则协议
# Obey robots.txt rules
ROBOTSTXT_OBEY = True# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32 #最大并发量32,默认16# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#下载延迟3秒
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16# Disable cookies (enabled by default)
#COOKIES_ENABLED = False# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False# Override the default request headers:
#请求头
#DEFAULT_REQUEST_HEADERS = {
#    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
#    "Accept-Language": "en",
#}# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    "mySpider.middlewares.MyspiderSpiderMiddleware": 543,
#}# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    "mySpider.middlewares.MyspiderDownloaderMiddleware": 543,
#}# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    "scrapy.extensions.telnet.TelnetConsole": None,
#}# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
#    "mySpider.pipelines.MyspiderPipeline": 300,
#}# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = "httpcache"
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = "scrapy.extensions.httpcache.FilesystemCacheStorage"# Set settings whose default value is deprecated to a future-proof value
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEED_EXPORT_ENCODING = "utf-8"

spiders

爬虫代码目录,定义了爬虫的逻辑

import scrapy
from mySpider.items import ItcastItemclass ItcastSpider(scrapy.Spider):name = "itcast"allowed_domains = ["iscast.cn"]start_urls = ["http://www.itcast.cn/"]def parse(self, response):# 获取网站标题list=response.xpath('//*[@id="mCSB_1_container"]/ul/li[@*]')

实战(大学信息)

目标网站:爬取大学信息

base64:

aHR0cDovL3NoYW5naGFpcmFua2luZy5jbi9yYW5raW5ncy9iY3VyLzIwMjQ=

变量命名

在刚刚创建的itcast里更改一下域名,在items里改一下接收数据格式

itcast.py

import scrapy
from mySpider.items import ItcastItemclass ItcastSpider(scrapy.Spider):name = "itcast"allowed_domains = ["iscast.cn"]start_urls = ["https://www.shanghairanking.cn/rankings/bcur/2024"]def parse(self, response):# 获取网站标题list=response.xpath('(//*[@class="align-left"])[position() > 1 and position() <= 31]')item=ItcastItem()for i in list:name=i.xpath('./div/div[2]/div[1]/div/div/span/text()').extract()description=i.xpath('./div/div[2]/p/text()').extract()location=i.xpath('../td[3]/text()').extract()item['name']=str(name).strip().replace('\\n','').replace(' ','')item['description']=str(description).strip().replace('\\n','').replace(' ','')item['location']=str(location).strip().replace('\\n','').replace(' ','')print(item)yield item

这里xpath感不太了解的可以看我之前的博客

一些爬虫基础知识备忘录-xpath

items.py

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.htmlimport scrapyclass ItcastItem(scrapy.Item):name = scrapy.Field()description=scrapy.Field()location=scrapy.Field()

pipelines.py

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html# useful for handling different item types with a single interface
import csv
from itemadapter import ItemAdapterclass MyspiderPipeline:def __init__(self):#在初始化函数中先创建一个csv文件self.f=open('school.csv','w',encoding='utf-8',newline='')self.file_name=['name','description','location']self.writer=csv.DictWriter(self.f,fieldnames=self.file_name)self.writer.writeheader()#写入第一段字段名def process_item(self, item, spider):self.writer.writerow(dict(item))#在写入的时候,要转化为字典对象print(item)return itemdef close_spider(self,spider):self.f.close()#关闭文件 

setting.py

# Scrapy settings for mySpider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#项目名称
BOT_NAME = "mySpider"SPIDER_MODULES = ["mySpider.spiders"]
NEWSPIDER_MODULE = "mySpider.spiders"# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = "mySpider (+http://www.yourdomain.com)"
#是否遵守规则协议
# Obey robots.txt rules
ROBOTSTXT_OBEY = False# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32 #最大并发量32,默认16# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#下载延迟3秒
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16# Disable cookies (enabled by default)
#COOKIES_ENABLED = False# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False# Override the default request headers:
#请求头
DEFAULT_REQUEST_HEADERS = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language": "en",
}# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    "mySpider.middlewares.MyspiderSpiderMiddleware": 543,
#}# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    "mySpider.middlewares.MyspiderDownloaderMiddleware": 543,
#}# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    "scrapy.extensions.telnet.TelnetConsole": None,
#}# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {"mySpider.pipelines.MyspiderPipeline": 300,
}
LOG_LEVEL = 'WARNING'
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = "httpcache"
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = "scrapy.extensions.httpcache.FilesystemCacheStorage"# Set settings whose default value is deprecated to a future-proof value
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEED_EXPORT_ENCODING = "utf-8"

start.py

然后在myspider文件夹下可以创建一个start.py文件,这样我们直接运行这个文件即可,不需要使用命令

from scrapy import cmdline
cmdline.execute("scrapy crawl itcast".split())

然后我们就正常保存为csv格式啦!

image-20250320113721472

一些问题

实现继续爬取,翻页

scrapy使用yield进行数据解析和爬取request,如果想实现翻页或者在请求完单次请求后继续请求,使用yield继续请求如果这里你使用一个return肯定会直接退出,感兴趣的可以去深入了解一下

一些setting配置

LOG_LEVEL = 'WARNING'可以把不太重要的日志关掉,让我们专注于看数据的爬取与分析

然后管道什么的在运行前记得开一下,把原先注释掉的打开就行

另外robot也要记得关一下

然后管道什么的在运行前记得开一下

文件命名

csv格式的文件命名一定要和items中的命名一致,不然数据进不去


到了结束的时候了,本篇文章是对scrapy框架的入门,更加深入的知识请期待后续文章,一起进步!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/898751.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

FastGPT 社区版快速部署指南

产品简介 FastGPT 是基于大语言模型的智能知识库系统&#xff0c;提供以下核心能力&#xff1a; ✅ 开箱即用 - 内置数据预处理、多模型对接、权限管理 ✅ 可视化编排 - 通过 Flow 工作流实现复杂问答逻辑设计 ✅ 多场景适配 - 支持客服机器人/知识检索/数据分析等场景 &…

【css酷炫效果】纯CSS实现科技感网格背景

【css酷炫效果】纯CSS实现科技感网格背景 缘创作背景html结构css样式完整代码基础版进阶版(3D光线扫描版) 效果图 想直接拿走的老板&#xff0c;链接放在这里&#xff1a;上传后更新 缘 创作随缘&#xff0c;不定时更新。 创作背景 刚看到csdn出活动了&#xff0c;赶时间&a…

vue3:十一、主页面布局(左侧菜单折叠展开设置)

一、实现效果 二、基本实现 1、菜单容器增加展开收缩方法 在菜单容器中开启这个方法&#xff0c;值设置为一个变量 :collapseiscollapse 2、定义菜单收缩与否的变量 在js中初始化是否收缩的变量&#xff0c;初始值为不收缩(也就是展开) //左侧菜单展开与收缩 const iscolla…

Chapter 4-15. Troubleshooting Congestion in Fibre Channel Fabrics

show zone member: Shows the name of the zone to which a device belongs to. This command can be used to find the victims of a culprit device or vice versa. 显示设备所属的区域名称。该命令可用于查找罪魁祸首设备的受害者,反之亦然。 show zone active: Shows the…

网络爬虫【爬虫库request】

我叫不三不四&#xff0c;很高兴见到大家&#xff0c;欢迎一起学习交流和进步 今天来讲一讲爬虫 Requests是Python的一个很实用的HTTP客户端库&#xff0c;完全满足如今网络爬虫的需求。与Urllib对比&#xff0c;Requests不仅具备Urllib的全部功能&#xff1b;在开发使用上&…

MTKAndroid12 解决SystemUI下拉框中,长按WIFI图标会导致崩溃问题

解决SystemUI下拉框中&#xff0c;长按WIFI图标会导致崩溃问题 文章目录 场景参考资料修改文件解决方案日志源码分析 总结 场景 在部分产品中偶发性发现&#xff0c; SystemUI下拉框下拉后长按WIFI图标会导致崩溃问题&#xff0c;有时候是截屏、点击Home 按键后&#xff0c;长…

XSS基础靶场练习

目录 1. 准备靶场 2. PASS 1. Level 1&#xff1a;无过滤 源码&#xff1a; 2. level2&#xff1a;转HTML实体 htmlspecialchars简介&#xff1a; 源码 PASS 3. level3:转HTML深入 源码&#xff1a; PASS 4. level4:过滤<> 源码&#xff1a; PASS: 5. level5:过滤on 源码…

熔断降级(Sentinel解决)

问题概述 在微服务架构中一定要预防微服务雪崩问题&#xff0c;微服务雪崩问题就是指在微服务架构中&#xff0c;当一个服务出现故障时&#xff0c;由于服务之间的依赖关系&#xff0c;故障可能会传播到其他服务&#xff0c;从而导致了大规模的服务失败&#xff0c;系统无法正…

TPCTF 2025 web 复现

文章目录 baby layoutsafe layoutSafe Layout Revengesupersqli baby layout 在index.js文件中&#xff0c;看到了有使用DOMPurify库来防止XSS操作 在package.json里可以看到版本是3.2.4,关于3.2.3是有绕过策略的。它会把script标签清除掉&#xff0c;去看bot可以看到flag是放…

Agent Team 多智能体系统解析

引言 在人工智能技术高速发展的今天&#xff0c;"多智能体协作系统"&#xff08;Agent Team&#xff09;正成为突破效率瓶颈的关键技术。与传统的单体AI不同&#xff0c;这种由多个专业化智能体组成的协同网络&#xff0c;通过分工协作和动态调整&#xff0c;展现出…

bootstrap 表格插件bootstrap table 的使用经验谈!

最近在开发一个物业管理软件&#xff0c;其中用到bootstrap 的模态框。同时需要获取表格数据。用传统的方法&#xff0c;本人不想用&#xff0c;考虑到bootstrap应该有获取表格数据的方法&#xff0c;结果发现要想实现获取表格数据功能&#xff0c;需要通过bootstrap的插件实现…

循环不变量原则——螺旋矩阵

题目&#xff1a;螺旋矩阵 本题相较于螺旋矩阵II的不同之处是&#xff1a;螺旋矩阵II的矩阵是n行n列的方阵&#xff0c;而本题的矩阵并不一定是方阵。所以在遵循循环不变量原则遍历完矩阵后&#xff0c;还会有一行或者一列没有遍历。 1、行多列少&#xff08;多一列没遍历&am…

【前端】Visual Studio Code安装配置教程:下载、汉化、常用组件、基本操作

文章目录 一、Visual Studio Code下载二、汉化三、常用组件1、Auto Rename Tag2、view-in-browser3、Live Server 四、基本操作五、感谢观看&#xff01; 一、Visual Studio Code下载 下载官网&#xff1a;https://code.visualstudio.com/ 进入官网后点击右上角的Download &…

Ubuntu22.04通过DKMS包安装Intel WiFi系列适配器(网卡驱动)

下载驱动包 访问 backport-iwlwifi-dkmshttps://launchpad.net/ubuntu/source/backport-iwlwifi-dkms 网站&#xff0c;找到适用于Ubuntu 22.04的update版本&#xff08;如backport-iwlwifi-dkms_xxxx_all.deb&#xff09;&#xff0c;下载至本地。 安装驱动 在下载目录中执行以…

kaggle上经典泰坦尼克项目数据分析探索

之前了解在kaggle上这个项目很火&#xff0c;最近想要加强一下python数据分析&#xff0c;所以在kaggle上找到这个项目进行学习探索&#xff0c;下面是将一些学习资料以及过程整理出来。 一、首先我们了解一下项目背景以及如何找到这个项目。 kaggle项目地址: https://www.k…

告别低效人工统计!自动计算计划进度

实时监控任务进度一直是项目管理中的一项巨大挑战。 人工统计方式不仅耗时耗力&#xff0c;而且往往由于信息传递的延迟和人为误差&#xff0c;导致无法实时获得准确的项目进展信息。 这种不准确性可能掩盖潜在的风险点&#xff0c;从而影响项目的整体进度和成果。 Ganttable …

楼宇自控系统的结构密码:总线与分布式结构方式的差异与应用

在现代建筑中&#xff0c;为了实现高效、智能的管理&#xff0c;楼宇自控系统变得越来越重要。它就像建筑的 智能管家&#xff0c;可自动控制照明、空调、通风等各种机电设备&#xff0c;让建筑运行更顺畅&#xff0c;还能节省能源成本。而在楼宇自控系统里&#xff0c;有两种关…

Docker逃逸

判断是否再docker中 1.ls -a / (查看c根目录查看是否有docker配置文件) 2.查看进程 如果在要逃逸到真实环境中&#xff1a; 特权模式进行docker逃逸&#xff1a;管理员执行eddocker run--privileg&#xff0c;如何判断是否是特权模式&#xff08;&#xff09; 特权模式以…

Vite管理的Vue3项目中monaco editer的使用以及组件封装

文章目录 背景环境说明安装流程以及组件封装引入依赖封装组件 外部使用实现效果 v-model实现原理 背景 做oj系统的时候,需要使用代码编辑器,决定使用Monaco Editor&#xff0c;但是因为自身能力问题&#xff0c;读不懂官网文档&#xff0c;最终结合ai和网友的帖子成功引入&…

PyCharm中使用pip安装PyTorch(从0开始仅需两步)

无需 anaconda&#xff0c;只使用 pip 也可以在 PyCharm 集成环境中配置深度学习 PyTorch。 本文全部信息及示范来自 PyTorch 官网。 以防你是super小白&#xff1a; PyCharm 中的命令是在 Python Console 中运行&#xff0c;界面左下角竖排图标第一个。 1. 安装前置包 numpy …