python爬取網頁轉換為PDF檔案

2022-10-04 19:30:20 字數 2507 閱讀 8285

爬蟲的起因

官方文件或手冊雖然可以查閱,但是如果變成紙質版的豈不是更容易翻閱與記憶。如果簡單的複製貼上,不知道何時能夠完成。於是便開始想著將android的官方手冊爬下來。

全篇的實現思路

參考資料:

* 把廖雪峰的教程轉換為pdf電子書

* requests文件

* beautiful soup文件

配置在ubuntu下使用pycharm執行成功

轉pdf需要**wkhtmltopdf

具體過程

網頁分析

如下所示的乙個網頁,要做的是獲取該網頁的正文和標題,以及左邊導航條的所有**

接下來的工作就是找到這些標籤嘍…

關於requests的使用

詳細參考文件,這裡只是簡單的使用requests獲取html以及使用**翻牆(**無法直接訪問,需要vpn)

proxies=

res程式設計客棧ponse=requests.get(url,proxies=proxies)

beautiful soup的使用

參考資料裡面有beautiful soup文件,將其看完後,可以知道就講了兩件事:乙個是查詢標籤,乙個是修改標籤。

本文需要做的是:

1. 獲取標題和所有的**,涉及到的是查詢標籤

#對標籤進行判斷,乙個標籤含有href而不含有description,則返回true

#而我希望獲取的是含有href屬性而不含有description屬性的標籤,(且只有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="n**")#獲取第乙個id為"n**"的標籤,這個裡面包含了**和標題

for i in tag.find_all(has_href_but_no_des):

s.append(i['href'])

title.append(i.text)

#獲取的只是標籤集,需要加html字首

htmls = ""

with open("android_training_3.html",'a') as f:

f.write(htmls)

對上面獲取的**分析,獲取正文,並將取出存於本地;涉及到的是查詢標籤和修改屬性

#網頁操作,獲取正文及

def get_htmls(urls,title):

for i in range(len(urls)):

response=requests.get(urls[i],proxies=proxies)

soup=bkrupleautifulsoup(response.content,"html.parser")

htmls="

" 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 kruplend"%(i,title[i]))

htmls=""

with open("android_training_3.html",'a') as f:

f.write(htmls)

2.轉為pdf

這一步需要**wkhtmltopdf,在windows下執行程式一直出錯..ubuntu下可以

def s**e_pdf(html):

"""把所有html檔案轉換成pdf檔案

"""options =

pdfkit.from_file(html, "android_training_3.pdf", options=options)

最後的效果圖

本文標題: python爬取網頁轉換為pdf檔案

本文位址: /jiaoben/python/229732.html

Python 爬取網頁

先謝郭嘉 以鏈家二手房為例 1.爬取網頁所必須的庫 import urllib.request import ssl 2.獲取預爬網頁資訊 1 網頁url 3.下面就可以爬取網頁了 以鏈家二手房為例 1.爬取網頁所必須的庫 import urllib.request import ssl 2.獲取預...

Python 爬取網頁資訊

對於本次學習爬蟲中的一些總結 1.要熟練掌握基礎知識,包括一些基礎的語法 2.正規表示式的正確使用,建議學習北理工的python爬蟲課程 3.先寫大框架再新增小的功能解析 4.對程式異常處理要熟練,盡量使用try.excep結構 5.對於列表字串資料的基本使用到位,比如增刪改查等 6.思路必須清晰 ...

Python 爬蟲爬取網頁

工具 python 2.7 import urllib import urllib2 defgetpage url 爬去網頁的方法 request urllib.request url 訪問網頁 reponse urllib2.urlopen request 返回網頁 return response...