確定需求(要爬取的內容是什麼?)
爬取CSDN文章內容 保存pdf
通過開發者工具進行抓包分析 分析數據從哪裡來的?
歡迎加入白嫖Q群:1039649593【電子書、源碼、課件、軟體、資料】都會分享
UP主解答問題VX:python10010
發送請求 對於文章列表頁面發送請求
獲取數據 獲取網頁原始碼
解析數據 文章的url 以及 文章標題
發送請求 對於文章詳情頁url地址發送請求
獲取數據 獲取網頁原始碼
解析數據 提取文章標題 / 文章內容
保存數據 把文章內容保存成html文件
把html文件轉成pdf文件
多頁爬取
導入模塊import requests # 數據請求 發送請求 第三方模塊 pip install requests
import parsel # 數據解析模塊 第三方模塊 pip install parsel
import os # 文件操作模塊
import re # 正則表達式模塊
import pdfkit # pip install pdfkit
filename = 'pdf\\' # 文件名字
filename_1 = 'html\\'
if not os.path.exists(filename): #如果沒有這個文件夾的話
os.mkdir(filename) # 自動創建一下這個文件夾
if not os.path.exists(filename_1): #如果沒有這個文件夾的話
os.mkdir(filename_1) # 自動創建一下這個文件夾
for page in range(1, 11):
print(f'=================正在爬取第{page}頁數據內容=================')
url = f'https://blog.csdn.net/qdPython/article/list/{page}'
# python代碼對於伺服器發送請求 >>> 伺服器接收之後(如果沒有偽裝)被識別出來, 是爬蟲程序, >>> 不會給你返回數據
# 客戶端(瀏覽器) 對於 伺服器發送請求 >>> 伺服器接收到請求之後 >>> 瀏覽器返回一個response響應數據
# headers 請求頭 就是把python代碼偽裝成瀏覽器進行請求
# headers參數欄位 是可以在開發者工具裡面進行查詢 複製
# 並不是所有的參數欄位都是需要的
# user-agent: 瀏覽器的基本信息 (相當於披著羊皮的狼, 這樣可以混進羊群裡面)
# cookie: 用戶信息 檢測是否登錄帳號 (某些網站 是需要登錄之後才能看到數據, B站一些數據內容)
# referer: 防盜鏈 請求你的網址 是從哪裡跳轉過來的 (B站視頻內容 / 妹子圖圖片下載 / 唯品會商品數據)
# 根據不同的網站內容 具體情況 具體分析
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'
}
# 請求方式: get請求 post請求 通過開發者工具可以查看url請求方式是什麼樣的
# 搜索 / 登錄 /查詢 這樣是post請求
response = requests.get(url=url, headers=headers)
# 需要把獲取到的html字符串數據轉成 selector 解析對象
selector = parsel.Selector(response.text)
# getall 返回的是列表
href = selector.css('.article-list a::attr(href)').getall()
for index in href:
# 發送請求 對於文章詳情頁url地址發送請求
response_1 = requests.get(url=index, headers=headers)
selector_1 = parsel.Selector(response_1.text)
title = selector_1.css('#articleContentId::text').get()
new_title = change_title(title)
content_views = selector_1.css('#content_views').get()
html_content = html_str.format(article=content_views)
html_path = filename_1 + new_title + '.html'
pdf_path = filename + new_title + '.pdf'
with open(html_path, mode='w', encoding='utf-8') as f:
f.write(html_content)
print('正在保存: ', title)
def change_title(name):
mode = re.compile(r'[\\\/\:\*\?\"\<\>\|]')
new_name = re.sub(mode, '_', name)
return new_name
config = pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
pdfkit.from_file(html_path, pdf_path, configuration=config)