网络爬虫 - 11 数据存储与分布式部署

数据存储与分布式爬取

1、CrawlSpider

CrawlSpider是一个类,scrapy里面有好多的爬虫类,基类就是Spider,CrawlSpider也是一个爬虫类,是Spider的子类。CrawlSpider比Spider强大,强大在可以提取链接,通过一个对象的方法来提取链接,写一个规则提取符合规则的链接。
    from scrapy.linkextractors import LinkExtractor
    链接提取器  LinkExtractor()
        创建对象过程
        le = LinkExtractor(allow=xxx, restrict_xpaths=xxx, restrict_css=xxx)
        allow : 正则表达式
        restrict_xpaths : 写一个xpath路径
        restrict_css : 写一个选择器

2、在scrapy shell中进行测试

(1)正则提取

le = LinkExtractor(allow=r'/8hr/page/\d+/')
le.extract_links(response)   查看提取结果

(2)xpath提取

le = LinkExtractor(restrict_xpaths='//ul[@class="pagination"]/li/a')
le = LinkExtractor(restrict_xpaths='//ul[@class="pagination"]/li')
le = LinkExtractor(restrict_xpaths='//ul[@class="pagination"]')

(3)css提取

le = LinkExtractor(restrict_css='.pagination > li > a')
le = LinkExtractor(restrict_css='.pagination > li')
le = LinkExtractor(restrict_css='.pagination')

(4)生成爬虫文件

scrapy genspider -t crawl qiuqiu www.qiushibaike.com

参见博客:
https://blog.csdn.net/zq602316498/article/details/37988683

3、动态ua和代理

通过中间件来实现
process_request(self, request, spider)
process_response(self, request, response, spider)
process_exception(self, request, exception, spider)
request.meta['download_timeout']
RETRY_ENABLED
RETRY_TIMES

4、存储到mysql、mongodb

from scrapy.utils.project import get_project_settings
settings = get_project_settings()
custom_settings = {}

5、redis配置

意思就是,假如现在两个电脑,windows,linux,redis服务安装在windows上面
打开redis的配置文件,第56行
bind 127.0.0.1   注释这一行
protected-mode no   yes修改为no
MongoDB可视化工具: robo 3T  https://robomongo.org/download
redis可视化工具:https://redisdesktop.com/download

6、存储到redis、分布式部署

分布式爬取:多台电脑同时爬取,假如一共800url,两台电脑,每个电脑爬取400url, scrapy是不能实现分布式的。

通过scrapy-redis组件进行实现

pip install scrapy-redis

配置:

我的windows是redis服务端
大家的windows是客户端、我的windows也是客户端
https://github.com/rmax/scrapy-redis

分布式:  对应关系
name === name
start_urls === redis_key
allowed_domains === __init__()  
【注】__init__()是一个坑,不能替换allowed_domains

运行:
scrapy runspider pic.py
向redis队列中添加一个起始url即可
lpush picspider:start_urls http://699pic.com/people.html

猜你喜欢

转载自blog.csdn.net/hanbo6/article/details/82183145