Scrap拥有高性能持久化存储,异步数据下载,高性能数据解析,分布式功能
配置:
- 安装 pip3 install scrapy
- 查看版本 scrapy version
- 创建项目 scrapy startproject xxx
- 创建spider scrapy genspider 爬虫名称 要爬虫的url入口
- 启动项目,cd进入项目一级目录,执行 scrapy crawl 爬虫名称
基础:
# 路径: game/game/spider/xiao.py中
class XiaoSpider(scrapy.Spider): #这个是自定义类XiaoSpider继承scrapy.Spider
def parse(self, response): #用来处理解析的函数
# 拿到页面源代码
# print(response.text)
li_list = response.xpath("//ul[@class='n-game cf']/li")
for li in li_list:
name = li.xpath("./a/b/text()").extract_first()
category = li.xpath("./em/a/text()").extract_first()
params = {
name,
category
}
yield params #利用生成器,将params传送到下一阶段,也就是传送到pipeline阶段中的管道内
break
# 路径:game/game/pipeline.py中,这个时候默认是不执行这里的,需要在setting中打开ITEM_PIPELINES
class GamePipeline:
def process_item(self, item, spider):
print(item)
return item
class CustomPipeline:
def process_item(self, item, spider):
item['abc'] = "测试"
return item
# 路径: game/settings
# 加上 LOG_LEVEL="WARNING" 表示控制台只输出警告和警告以上级别的信息
# 这个时候默认是不执行这里的,需要在setting中打开ITEM_PIPELINES
ITEM_PIPELINES = {
"game.pipelines.GamePipeline": 300,
"game.pipelines.CustomPipeline": 299,
}
"game.pipelines.GamePipeline":这个代表管道路径,
300代表优先级顺序,数字越小,越先执行
- extract_first:提取第一项,如果没有则返回None
配置文件:settings.py
-
LOG_LEVEL="WARNING" 表示控制台只输出警告和警告以上级别的信息
-
ROBOTSTXT_OBEY=True 表示如果网站的robots中写的不让爬取,则scrapy不会爬取