Python爬虫批量下载PDF文档
生活随笔
收集整理的這篇文章主要介紹了
Python爬虫批量下载PDF文档
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
- 0. 需求
- 1. 網(wǎng)頁(yè)源代碼分析
- 2. 程序流程
- 3. 代碼
0. 需求
有人通過(guò)云盤(pán)映射分享了一批非掃描PDF文檔http://pan.win10sys.com/電子書(shū)/Books(White%20prostitute),激發(fā)了我的“倉(cāng)鼠”屬性——我要保存到自己手里。但是這種分享不支持批量下載,一個(gè)一個(gè)下載也太low了,要不寫(xiě)個(gè)爬蟲(chóng)批量下載?
1. 網(wǎng)頁(yè)源代碼分析
可以看到結(jié)構(gòu)很簡(jiǎn)單,一個(gè)<a>(超鏈接)標(biāo)簽,非常適合BeautifulSoup。它可以切分出指定標(biāo)簽的內(nèi)容,并按字典格式存儲(chǔ)。
2. 程序流程
3. 代碼
from bs4 import BeautifulSoup import urllib.request import requests#獲取網(wǎng)頁(yè)源代碼 def getHtml(url):req = urllib.request.Request(url)webpage = urllib.request.urlopen(req)html = webpage.read()return html#下載文件 def downloadPDF(url, title):#get請(qǐng)求file = requests.get(url)with open(title, "wb") as code:code.write(file.content)urlRoot = "電子書(shū)/Books(White%20prostitute)/電子工業(yè)出版社" #鏈接中含有漢字需要轉(zhuǎn)換一下格式 #但是會(huì)智障的把':'也轉(zhuǎn)換,導(dǎo)致無(wú)法識(shí)別,所以先轉(zhuǎn)換再拼接 urlRoot = urllib.parse.quote(urlRoot) #獲取網(wǎng)頁(yè)源代碼 htmlRoot = getHtml('http://pan.win10sys.com/' + urlRoot) #解析 soup = BeautifulSoup(htmlRoot, 'html.parser') #依次查找<a>標(biāo)簽 for k in soup.find_all('a'):#print(k)#剔除不含class屬性的標(biāo)簽if (k.string is not 'GitHub') or (k.string is not '管理'): #只讀取PDF超鏈,即class屬性是['classfix']if k['class'] == ['clearfix']:#print('http://pan.win10sys.com' + k['href'])#拼接鏈接并讀取html = getHtml('http://pan.win10sys.com/' + k['href'])#title就是書(shū)名title = k['title']#解析PDF下載頁(yè)面 soup2 = BeautifulSoup(html, 'html.parser')#依次查找<a>標(biāo)簽for k2 in soup2.find_all('a'):#只讀取下載超鏈,即class屬性是['download-menu']if k2['class'] == ['download-menu']:downloadPDF(k2['href'], title)print("success:" + " " + title)else:print("剔除:" + ' ' + k)else:print("剔除:" + ' ' + k)總結(jié)
以上是生活随笔為你收集整理的Python爬虫批量下载PDF文档的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ios app应用开发环境配置方法总结
- 下一篇: python编写arcgis脚本教程_零