問題:網頁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中