上篇我们记录了Scrapy的各个组件功能,这篇我们来动手scrapy爬虫框架的依赖库搭建和项目创建,开始进入进阶实战。
pip install lxml==4.9.2
pip install parsel==1.6.0
pip install Twisted==21.2.0
pip install pyOpenSSL==19.1.0
pip install cryptography==2.8
pip install Scrapy==1.6.0
以上依赖库是必须要安装的,否则启动Scrapy会报依赖包不存在的错;Scrapy的依赖包对版本要求比较严格,不同版本的依赖包经常会冲突,上面这些依赖包是测试过没有问题的。
scrapy startproject scrapy_demo
from scrapy import cmdline
if __name__ == '__main__':
cmdline.execute("scrapy crawl demo_spider".split())
# -*- coding: utf-8 -*-
import scrapy
class DemoSpider(scrapy.Spider):
name = "demo_spider"
def start_requests(self):
urls = [
'http://quotes.toscrape.com/page/1/',
'http://quotes.toscrape.com/page/2/',
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
page = response.url.split("/")[-2]
filename = f'quotes-{page}.html'
with open(filename, 'wb') as f:
f.write(response.body)
self.log(f'Saved file {filename}')