问题:网页http://gk.chengdu.gov.cn/govInfo/detail.action?id=2653973&tn=2中有一个PDF需要下载,开发者模式下该PDF的链接为http://gk.chengdu.gov.cn/uploadfiles/07180246020404/2020061116272871.pdf,如何下载该PDF保存为本地文件文件?
1)进入scrapy shell
scrapy shell
2)爬取该PDF所在的网页URL
shell模式下用方法fetch
fetch('http://gk.chengdu.gov.cn/govInfo/detail.action?id=2653973&tn=2')
爬取到网页内容全部保存在了response中
3)通过XPath提取PDF的链接
In [5]: response.xpath('.//a[starts-with(@class,"ke")]/@href').extract()[0] Out[5]: 'http://gk.chengdu.gov.cn/uploadfiles/07180246020404/2020061116272871.pdf'
4)通过fetch请求该URL,得到response,PDF内容就都保存在了该response中,通过response.body提取
with open('abc.pdf','wb')as f: f.write(response.body)
5)这样内容就写入了PDF文件abc.pdf中