爬蟲的起因
官方文檔或手冊雖然可以查閱,但是如果變成紙質版的豈不是更容易翻閱與記憶。如果簡單的復制粘貼,不知道何時能夠完成。于是便開始想著將Android的官方手冊爬下來。
全篇的實現思路
- 分析網頁
- 學會使用BeautifulSoup庫
- 爬取并導出
參考資料:
* 把廖雪峰的教程轉換為PDF電子書
* Requests文檔
* Beautiful Soup文檔
配置
在Ubuntu下使用Pycharm運行成功
轉PDF需要下載wkhtmltopdf
具體過程
網頁分析
如下所示的一個網頁,要做的是獲取該網頁的正文和標題,以及左邊導航條的所有網址
接下來的工作就是找到這些標簽嘍…
關于Requests的使用
詳細參考文檔,這里只是簡單的使用Requests獲取html以及使用代理翻墻(網站無法直接訪問,需要VPN)
1
2
3
4
5
6
|
proxies = { "http" : "http://vpn的IP:port" , "https" : "https://vpn的IP:port" , } response = requests.get(url,proxies = proxies) |
Beautiful Soup的使用
參考資料里面有Beautiful Soup文檔,將其看完后,可以知道就講了兩件事:一個是查找標簽,一個是修改標簽。
本文需要做的是:
1. 獲取標題和所有的網址,涉及到的是查找標簽
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#對標簽進行判斷,一個標簽含有href而不含有description,則返回true #而我希望獲取的是含有href屬性而不含有description屬性的<a>標簽,(且只有a標簽含有href) def has_href_but_no_des(tag): return tag.has_attr( 'href' ) and not tag.has_attr( 'description' ) #網頁分析,獲取網址和標題 def parse_url_to_html(url): response = requests.get(url,proxies = proxies) soup = BeautifulSoup(response.content, "html.parser" ) s = [] #獲取所有的網址 title = [] #獲取對應的標題 tag = soup.find( id = "nav" ) #獲取第一個id為"nav"的標簽,這個里面包含了網址和標題 for i in tag.find_all(has_href_but_no_des): s.append(i[ 'href' ]) title.append(i.text) #獲取的只是標簽集,需要加html前綴 htmls = "<html><head><meta charset='UTF-8'></head><body>" with open ( "android_training_3.html" , 'a' ) as f: f.write(htmls) |
對上面獲取的網址分析,獲取正文,并將圖片取出存于本地;涉及到的是查找標簽和修改屬性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#網頁操作,獲取正文及圖片 def get_htmls(urls,title): for i in range ( len (urls)): response = requests.get(urls[i],proxies = proxies) soup = BeautifulSoup(response.content, "html.parser" ) htmls = "<div><h1>" + str (i) + "." + title[i] + "</h1></div>" tag = soup.find( class_ = 'jd-descr' ) #為image添加相對路徑,并下載圖片 for img in tag.find_all( 'img' ): im = requests.get(img[ 'src' ], proxies = proxies) filename = os.path.split(img[ 'src' ])[ 1 ] with open ( 'image/' + filename, 'wb' ) as f: f.write(im.content) img[ 'src' ] = 'image/' + filename htmls = htmls + str (tag) with open ( "android_training_3.html" , 'a' ) as f: f.write(htmls) print ( " (%s) [%s] download end" % (i,title[i])) htmls = "</body></html>" with open ( "android_training_3.html" , 'a' ) as f: f.write(htmls) |
2.轉為PDF
這一步需要下載wkhtmltopdf,在Windows下執行程序一直出錯..Ubuntu下可以
1
2
3
4
5
6
7
8
9
10
11
12
|
def save_pdf(html): """ 把所有html文件轉換成pdf文件 """ options = { 'page-size' : 'Letter' , 'encoding' : "UTF-8" , 'custom-header' : [ ( 'Accept-Encoding' , 'gzip' ) ] } pdfkit.from_file(html, "android_training_3.pdf" , options = options) |
最后的效果圖
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/molu_chase/article/details/77508260