scrapy分页抓取网页(scrapy,分析源码结构分析页面html结构下载器流程)
优采云 发布时间: 2021-12-24 17:06scrapy分页抓取网页(scrapy,分析源码结构分析页面html结构下载器流程)
Scrapy内部提供了FilesPipeline来下载文件,我们可以把它看成一个特殊的下载器,只要传入要下载的文件的url,下载器就会自动将文件下载到本地
流程简单
我们用伪代码来说明下载过程,假设我们要下载如下页面的文件
GEM专辑
下载《偶尔》
下载《一路逆风》
下载《来自天堂的魔鬼》
下载上述mp3文件的步骤如下:
在settings.py中打开FilesPipeline并指定下载路径
ITEM_PIPELINES = {'scrapy.pipelines.files.FilesPipeline': 1}
FILES_STORE = '/music_downloads'
FilesPipeline 应该放在其他 Item Pipeline 之前
Spider解析页面,提取要下载的url并赋值给item的file_urls字段
伪代码如下:
class DownloadMusicSpider(scrapy.Spider):
# ...
def parse(response):
item = {}
# 提取 url 组装成列表,并赋给 item 的 file_urls 字段
for url in response.xpath('//a/@href').extract():
download_url = response.urljoin(url)
item['file_urls'].append(download_url)
yield item
项目实际需求分析
是一个著名的python绘图库,每个例子都有对应的源码下载,如:
下载源代码
我们的需求是抓取matplotlib的示例代码,下载保存到本地
写代码前,使用scrapy shell分析源码结构
$ scrapy shell http://matplotlib.org/examples/index.html
# ...
In [1]: view(response) # 将页面下载到本地,分析其 html 结构
Out[1]: True
分析页面html结构
分析显示所有示例链接都在
在以下每个
在scrapy shell中提取链接
In [2]: from scrapy.linkextractors import LinkExtractor
In [3]: le = LinkExtractor(restrict_css='div.toctree-wrapper.compound li.toctree-l2')
In [4]: links = le.extract_links(response)
In [5]: [link.url for link in links]
Out[5]:
['https://matplotlib.org/examples/animation/animate_decay.html',
'https://matplotlib.org/examples/animation/basic_example.html',
'https://matplotlib.org/examples/animation/basic_example_writer.html',
'https://matplotlib.org/examples/animation/bayes_update.html',
# ...
]
然后分析具体示例页面,提取下载源代码的url
In [6]: fetch('https://matplotlib.org/examples/animation/animate_decay.html')
2019-07-21 22:15:22 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None)
In [7]: view(response)
Out[7]: True
下载页面html结构
分析显示下载url是在元素中获取的
In [8]: href = response.css('a.reference.external::attr(href)').extract_first()
In [9]: href
Out[9]: 'animate_decay.py'
In [10]: response.urljoin(href) # 组装成绝对地址
Out[10]: 'https://matplotlib.org/examples/animation/animate_decay.py'
实现项目创建的具体编码
本文参与腾讯云自媒体分享计划,欢迎您加入,与正在阅读的您分享。