用python爬蟲批量下載pdf的實現
阿新 • • 發佈:2020-12-03
今天遇到一個任務,給一個excel檔案,裡面有500多個pdf檔案的下載連結,需要把這些檔案全部下載下來。我知道用python爬蟲可以批量下載,不過之前沒有接觸過。今天下午找了下資料,終於成功搞定,免去了手動下載的煩惱。
由於我搭建的python版本是3.5,我學習了上面列舉的參考文獻2中的程式碼,這裡的版本為2.7,有些語法已經不適用了。我修正了部分語法,如下:
# coding = UTF-8 # 爬取李東風PDF文件,網址:http://www.math.pku.edu.cn/teachers/lidf/docs/textrick/index.htm import urllib.request import re import os # open the url and read def getHtml(url): page = urllib.request.urlopen(url) html = page.read() page.close() return html # compile the regular expressions and find # all stuff we need def getUrl(html): reg = r'(?:href|HREF)="?((?:http://)?.+?\.pdf)' url_re = re.compile(reg) url_lst = url_re.findall(html.decode('gb2312')) return(url_lst) def getFile(url): file_name = url.split('/')[-1] u = urllib.request.urlopen(url) f = open(file_name,'wb') block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break f.write(buffer) f.close() print ("Sucessful to download" + " " + file_name) root_url = 'http://www.math.pku.edu.cn/teachers/lidf/docs/textrick/' raw_url = 'http://www.math.pku.edu.cn/teachers/lidf/docs/textrick/index.htm' html = getHtml(raw_url) url_lst = getUrl(html) os.mkdir('ldf_download') os.chdir(os.path.join(os.getcwd(),'ldf_download')) for url in url_lst[:]: url = root_url + url getFile(url)
上面這個例子是個很好的模板。當然,上面的還不適用於我的情況,我的做法是:先把地址寫到了html檔案中,然後對正則匹配部分做了些修改,我需要匹配的地址都是這樣的,http://pm.zjsti.gov.cn/tempublicfiles/G176200001/G176200001.pdf。改進後的程式碼如下:
# coding = UTF-8 # 爬取自己編寫的html連結中的PDF文件,網址:file:///E:/ZjuTH/Documents/pythonCode/pythontest.html import urllib.request import re import os # open the url and read def getHtml(url): page = urllib.request.urlopen(url) html = page.read() page.close() return html # compile the regular expressions and find # all stuff we need def getUrl(html): reg = r'([A-Z]\d+)' #匹配了G176200001 url_re = re.compile(reg) url_lst = url_re.findall(html.decode('UTF-8')) #返回匹配的陣列 return(url_lst) def getFile(url): file_name = url.split('/')[-1] u = urllib.request.urlopen(url) f = open(file_name,'wb') block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break f.write(buffer) f.close() print ("Sucessful to download" + " " + file_name) root_url = 'http://pm.zjsti.gov.cn/tempublicfiles/' #下載地址中相同的部分 raw_url = 'file:///E:/ZjuTH/Documents/pythonCode/pythontest.html' html = getHtml(raw_url) url_lst = getUrl(html) os.mkdir('pdf_download') os.chdir(os.path.join(os.getcwd(),'pdf_download')) for url in url_lst[:]: url = root_url + url+'/'+url+'.pdf' #形成完整的下載地址 getFile(url)
這就輕鬆搞定啦。
我參考了以下資料,這對我很有幫助:
1、廖雪峰python教程
2、用Python 爬蟲批量下載PDF文件
3、用Python 爬蟲爬取貼吧圖片
4、Python爬蟲學習系列教程
到此這篇關於用python爬蟲批量下載pdf的實現的文章就介紹到這了,更多相關python爬蟲批量下載pdf內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!