我們有時候看到一篇好的文章,想去保存下來,傳統方式一般是收藏書簽、復制粘貼到檔案或者直接復制鏈接保存,但這樣一次兩次還好,數量多了,比較麻煩不說,還可能不好找~

這個時候,Python的作用就來了,直接抓下來匯出為PDF,直接把整個網站的內容都導下來都行~

話不多說,我們直接上代碼!
import requests import parsel import pdfkit import os import re html_str = """ <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> {article} </body> </html> """ def change_title(title): """ python學習交流群:279199867 替換標題中的特殊字符 :param title: 傳入文章標題 :return: 回傳一個替換掉特殊字符的標題 """ """ 使用re.compile()將正則運算式的字串形式編譯為一個物件,通過該物件提供的一些列方法對文本 進行匹配查找 re.sub() 第一個引數對應的正則運算式,第二個引數為要替換成的字串, 第三個引數為源字串 """ pattern = re.compile(r"[\/\\\:\*\?\"\<\>\|]") # '/ \ : * ? " < > |' new_title = re.sub(pattern, "_", title) # 替換為下劃線 return new_title for page in range(1, 11): """ 發送請求的url地址,唯一資源定位符 headers: 請求頭 把python偽裝成瀏覽器對服務器發送請求, 然后服務器會給我們回傳一個回應資料 請求頭所加的引數都是可以在開發者工具中的headers里面的request headers中找到的 比如 user-agent:代表著瀏覽器的資訊 cookies:用戶的資訊 常用于檢測是否有登陸賬號 host:域名 referer:常說的防盜鏈,告訴服務器是從哪個網頁跳轉過來的 請求方式:可以通過開發者工具中headers里面的資料看到是什么樣的請求方式 get請求: 是可以直接從服務器上面獲取資料 post請求:需要向服務器發送一個資料 比如說(搜索/登陸) response:回應物件 狀態碼: 200表示請求成功 300:重定向 跳轉 400:通常是url網址不對 500 一般是服務器問題 獲取網頁文本資料 response.text 獲取網頁json字典資料 response.json() 獲取網頁二進制資料 response.content """ url = 'https://blog.csdn.net/qdPython/article/list/{page}' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36' } response = requests.get(url=url, headers=headers) """ 把 html 字串資料轉換成一個 Selector 物件 Selector 就具有一系列資料決議的方法 css/xpath/re 類選擇器 都是使用圓點.開頭 ID選擇器 是使用#開頭 屬性選擇器: ::text獲取標簽里面的文本資料 ::attr(xxx) 獲取標簽內某一個屬性的資料 get() 從 Selector 物件中提取第一個資料, 直接回傳字串資料給我們 getall() 從 Selector 物件中提取提取所有資料, 回傳一個串列 """ selector = parsel.Selector(response.text) href = selector.css('.article-list div.article-item-box a::attr(href)').getall() for link in href: response_1 = requests.get(url=link, headers=headers) selector_1 = parsel.Selector(response_1.text) title = selector_1.css('#articleContentId::text').get() content = selector_1.css('#content_views').get() new_title = change_title(title) # 創建檔案保存地址以及保存檔案的名字 和格式 pdf_path = 'pdf\\' + new_title + '.pdf' html_path = 'pdf\\' + new_title + '.html' # str.format() 字串格式化方法 html = html_str.format(article=content) """ with open 打開檔案時, 當檔案物件參考完畢之后會自動關閉檔案 html_path:檔案保存路徑以及名字格式 mode:保存方式 w 寫入 如果你不寫mode默認是r 讀 encoding: 編碼 as f 重命名 可以自定義 f = open() f.writer() f.close() """ with open(html_path, mode='w', encoding='utf-8') as f: f.write(html) print('正在保存:', title) # exe 檔案存放的路徑 config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe') # 把 html 通過 pdfkit 變成 pdf 檔案 pdfkit.from_file(html_path, pdf_path, configuration=config) os.remove(html_path)
兄弟們快去試試吧!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/481527.html
標籤:Python
上一篇:在角度代碼中,foreach回圈在完成回圈迭代之前跳到另一個函式
下一篇:加入的附加條件
