本篇文章流程(爬蟲基本思路):
一. 資料來源分析 (只有當你找到資料來源的時候, 才能通過代碼實作)
- 確定需求(要爬取的內容是什么?)
爬取CSDN文章內容 保存pdf - 通過開發者工具進行抓包分析 分析資料從哪里來的?
Python從零基礎入門到實戰系統教程、原始碼、視頻,想要資料集的同學也可以點這里
二. 代碼實作程序
- 發送請求 對于文章串列頁面發送請求
- 獲取資料 獲取網頁源代碼
- 決議資料 文章的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 = https://www.cnblogs.com/qshhl/p/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
運行代碼,即可下載HTML檔案

轉換成PDF檔案
config = pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe') pdfkit.from_file(html_path, pdf_path, configuration=config)

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/296028.html
標籤:Python
