1. 程式人生 > >網絡爬蟲——針對任意主題批量爬取PDF

網絡爬蟲——針對任意主題批量爬取PDF

open 代碼 針對 得到 搜索結果 pre ner tps -c

|本文為博主原創,轉載請說明出處

任務需求要求通過Google針對任意關鍵字爬取大量PDF文檔,如K-means,KNN,SVM等。

環境:Anaconda3——Windows7-64位——Python3.6——lantern——迅雷極速版——360瀏覽器

先貼代碼

 1 # -*- coding: utf-8 -*-
 2 import urllib.request
 3 import re#導入正則表達式包
 4 import time
 5 
 6 #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 url_part_1="https://www.google.co.jp/search?q=svm+filetype:pdf&lr=&hl=zh-CN&as_qdr=all&ei=VIdnWZ3SGIS18QXW3aAg&start=" 8 url_part_2="&sa=N&biw=1745&bih=810" 9 Page_number=28 #每一個搜索結果的頁數,這個針對不同的主題結果會不一樣 10 #這幾行代碼針對不同的主題要進行相應的修改,稍後再解釋url_part_1和url_part_2的意思 11 #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12 13 timeout=20 #請求時間20秒 14 sleep_download_time=5 #爬一個網頁休息5秒鐘,這樣有利於不被Google認為是攻擊行為,當然,這只是一個方面 15 url_list_total=[]#將所有pdf文檔的鏈接地址放在這個列表當中 16 user_agent = Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36 17 #這個是我的360瀏覽器的user_agent,按F12可查 18 19
for i in range(0,Page_number): 20 url_page=url_part_1+str(i*10)+url_part_2#拼接成每個Google搜索結果的頁面地址 21 headers = { User-Agent : user_agent,Referer:url_page} 22 request= urllib.request.Request(url_page,headers=headers) 23 try:#可能會出現異常[WinError 10054] 24 page = urllib.request.urlopen(request,timeout=timeout) 25 except urllib.error.URLError as e: 26 print(e.reason) 27 28 html= page.read().decode(utf-8)#必須要有.decode(‘utf-8‘) 29 pattern = re.compile(<h3 class="r".*?<a href="(.*?)" onmousedown)#這個表達式主要是為了獲取pdf的鏈接地址 30 url_list=re.findall(pattern,html) 31 32 for line in url_list[:]: 33 url_list_total.append(line) 34 url_list=[] 35 print(page.getcode()) 36 print(i) 37 page.close() 38 html=[] 39 time.sleep(sleep_download_time)#隔幾秒再運行 40 41 f=open(url_list_total.txt,w) 42 for url in url_list_total: 43 f.write(url) 44 f.write(\n) 45 f.close()

下面解釋一下7-8行,通過Google搜索的結果的地址是有規律的,如通過關鍵字svm filetype:pdf返回的結果的第一頁地址如下

https://www.google.co.jp/search?q=svm+filetype:pdf&lr=&hl=zh-CN&as_qdr=all&ei=VIdnWZ3SGIS18QXW3aAg&start=10&sa=N&biw=1745&bih=810

做如下拆分

"https://www.google.co.jp/search?q=svm+filetype:pdf&lr=&hl=zh-CN&as_qdr=all&ei=VIdnWZ3SGIS18QXW3aAg&start=" + 10 + "&sa=N&biw=1745&bih=810"

分成三部分,方便後面進行叠代。

這樣得到所有的pdf的鏈接下載地址之後就可以通過迅雷批量下載啦!

網絡爬蟲——針對任意主題批量爬取PDF