Python scrapy

139 阅读2分钟

24.08.21

文档

docs.scrapy.org/en/latest/i… 文档中的settings很重要

记录一下我感到一些有困惑的点

解释: scrapy框架通用爬虫(scrapy.Spider)、深度爬虫(RedisSpider)、分布式爬虫(CrawlSpider)、分布式深度爬虫(RedisCrawlSpider) developer.aliyun.com/article/693…

1. 创建crawl project

运行 scrapy startproject tutorial 命令

在project项目目录外, project项目同级目录下执行

多创建几次项目,就有几个project

2. 测试

- 简单的命令行界面 scrapy shell "https://quotes.toscrape.com/page/1/" css or path 测试

- 复杂的项目中断点查看

3. 运行方式4种

(转)www.cnblogs.com/luo630/p/92…

在创建了爬虫程序后,就可以运行爬虫程序了。

Scrapy中介绍了几种运行爬虫程序的方式,列举如下:

- 1. 命令行工具之scrapy runspider(全局命令)

语法:scrapy runspider <spider_file.py>
还有一些配置项,可以使用scrapy runspider -h查看。

- 2. 命令行工具之scrapy crawl(项目级命令)

scrapy crawl <spider> // spider是crawl的名字

- 3. scrapy.crawler.CrawlerProcess (recommend)

import scrapy
from scrapy.crawler import CrawlerProcess
from baidu_com import BaiduComSpider

# 创建一个CrawlerProcess对象
process = CrawlerProcess() # 括号中可以添加参数

process.crawl(BaiduComSpider)
process.start()

使用get_project_settings()函数获取项目的一个Settings实例作为CrawlerProcess的参数,传递给crawl(...)函数的可以是项目内爬虫程序的name属性的值

import os
import sys

from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

settings = get_project_settings()
crawler = CrawlerProcess(settings)

crawler.crawl('alexa')

if __name__ == '__main__':
    crawler.start()
    pass

- 4. scrapy.crawler.CrawlerRunner

官文对CrawlerRunner有更详细的介绍

from twisted.internet import reactor
import scrapy
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from baidu_com import BaiduComSpider
from techmeme_com import TechmemeComSpider

configure_logging()

# 创建一个CrawlerRunner对象
runner = CrawlerRunner()

runner.crawl(BaiduComSpider)
runner.crawl(TechmemeComSpider)
d = runner.join() # 在多线程编程中见到过此函数,这里是?
d.addBoth(lambda _: reactor.stop()) # addBoth参考Derrerred的文档
reactor.run()

4. 练手项目

1. github.com/rmax/scrapy…

由Redis接管控制请求的队列,方便做到分布式部署
调度器重写了, SCHEDULER = "scrapy_redis.scheduler.Scheduler"

2. 7-8年的项目, 练手刚刚好, 很推荐

https://github.com/geekan/scrapy-examples
https://github.com/taizilongxu/scrapy_jingdong 
https://github.com/lihansunbai/Fang_Scrapy
https://github.com/OFZFZS/scrapy-pinduoduo
https://github.com/lihansunbai/Fang_Scrapy
https://github.com/scrapy/quotesbot

3. 基于 scrapyd

// scrapyd
https://github.com/scrapy/scrapyd  

https://github.com/my8100/scrapydweb
https://github.com/DormyMo/SpiderKeeper
https://github.com/scrapinghub/scrapyrt

4. Selenium+scrapy 界面爬取

https://github.com/seleniumbase/SeleniumBase
https://github.com/clemfromspace/scrapy-selenium

5. 代理池 proxies

https://github.com/TeamHG-Memex/scrapy-rotating-proxies
https://github.com/SpiderClub/haipproxy
https://github.com/aivarsk/scrapy-proxies

6. github.com/coder-hxl/x…

可以试试, 可以用来生成模式

7. github.com/scrapinghub…

可以参考实现原理, (不推荐) , 很久没有更新了, Portia 图形结合的爬虫