Scrapy基本使用
Scrapy基本使用
环境准备
pip install scrapy
项目操作
在当前目录创建scrapy项目scrapy startproject [project_name]
scrapy startproject test_scrapy
进入项目目录,生成爬虫文件scrapy genspider [name] [url]
scrapy genspider first www.xxx.com
运行项目scrapy crawl [name]
scrapy crawl first
配置文件
1 | USER_AGENT设置UA |
数据解析
获取定位到的首个标签response.xpath().get()
获取定位到的所有标签,返回列表response.xpath().getall()
持久化存储
基于指令的持久化存储
存储parse函数的返回值,仅支持部分文件后缀scrapy crawl first -o test.csv
基于管道的持久化存储
配置文件中加入ITEM_PIPELINES
1
2
3ITEM_PIPELINES = {
"test_scrapy.pipelines.TestScrapyPipeline": 300,
}定义item类
1
2
3
4
5
6import scrapy
class TestScrapyItem(scrapy.Item):
# 按如下格式写
# name = scrapy.Field()
title = scrapy.Field()实例化item类并提交给管道
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import scrapy
from test_scrapy.items import TestScrapyItem
class FirstSpider(scrapy.Spider):
name = "first"
#定义作用域
#allowed_domains = ["www.xxx.com"]
#指定请求的url
start_urls = ["https://movie.douban.com/"]
def parse(self, response):
titles = response.xpath('//li[@class="title"]/a/text()').getall()
for title in titles:
item = TestScrapyItem()
item["title"] = title
#提交item给管道
yield item定义管道类
文件存储
1 | from itemadapter import ItemAdapter |
整合mysql进行数据库存储
1 | from itemadapter import ItemAdapter |
如果要同时在多个平台存储,只需在pipelines.py中定义多个管道类,并在配置文件中的ITEM_PIPELINES加入类名和优先级
将新的请求加入请求队列
1 | def parse(self, response): |
请求传参
1 | #自定义 |
图片爬取
使用ImagesPipeline
配置文件添加存储路径
IMAGES_STORE = "imgs"
parse函数中提交item,包含图片url
定义管道类
1
2
3
4
5
6
7
8
9
10
11
12
13
14from itemadapter import ItemAdapter
from scrapy.pipelines.images import ImagesPipeline
import scrapy
class ImgPipeline(ImagesPipeline):
#根据图片url发送请求
def get_media_requests(self, item, info):
yield scrapy.Request(url=item["img_url"])
#指定图片存储名
def file_path(self, request, response=None, info=None, *, item=None):
return item["img_url"].split("/")[-1]
#传给下一个管道
def item_completed(self, results, item, info):
return item
下载中间件
作用:拦截请求和响应
首先修改配置文件,启用下载中间件
1 | class ImgProDownloaderMiddleware: |
下载中间件整合selenium获取动态加载的数据
爬虫文件
1 | from selenium import webdriver |
下载中间件
1 | from scrapy import signals |
CrawlSpider全站数据爬取
- 创建工程
- 创建爬虫文件(CrawlSpider)
scrapy genspider -t crawl [name] [url]
- 爬虫文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class SunSpider(CrawlSpider):
name = "sun"
#allowed_domains = ["www.xxx.com"]
start_urls = ["https://wz.sun0769.com/political/index/politicsNewest?id=1&page=1"]
#allow是正则表达式
#LinkExtractor根据指定的规则提取连接
#满足的url返回的response会传给callback函数
#follw表示是否递归爬取
rules = (Rule(LinkExtractor(allow=r"id=1&page=\d+"), callback="parse_item", follow=True),)
def parse_item(self, response):
item = {}
return item
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 lswtn!