知識點:
- requests
- css選擇器
第三方庫:
- requests >>> pip install requests
- parsel >>> pip install parsel
- pdfkit >>> pip install pdfkit
開發環境:
- 版 本:anaconda5.2.0(python3.6.5)
- 編輯器:pycharm (安裝包/安裝教程/激活碼/使用教程/插件[翻譯插件/主題/漢化包])
- 軟體環境: wkhtmltopdf 把html檔案轉成pdf
【付費VIP完整版】只要看了就能學會的教程,80集Python基礎入門視頻教學
本節課上課流程思路:
一. 資料來源分析
確定要爬目標: 檔案內容
這些檔案資料內容是可以從哪里獲取的
分析資料的程序:
- 滑鼠右鍵點擊檢查或者F12 打開開發者工具 選擇 network
- 通過開發者工具進行搜索(相關一些資料) 雖然回傳資料 (字體編碼)
- 搜索沒有回傳資料 可以查看本身網址發送請求 服務器回傳的資料內容
- 分析多個文章的url地址區別 請求url地址情況
二. 代碼實作程序
- 發送請求, 對于文章串列頁面發送請求
- 獲取資料, 獲取網頁源代碼
- 決議資料, 提取文章url地址或者文章標題
- 發送請求, 對于文章詳情頁url地址發送請求
- 獲取資料, 獲取網頁源代碼
- 決議資料, 提取文章內容
- 保存資料, 保存成html檔案內容
- 保存PDF, 需要把html檔案轉成PDF檔案內容
- 多頁爬取
匯入模塊
import requests # 資料請求模塊 第三方模塊 pip install requests 在CMD里面即可安裝 import parsel # 資料決議模塊 第三方模塊 pip install parsel import os # 檔案操作模塊 內置模塊 import pdfkit
1. 發送請求, 對于文章串列頁面發送請求
# 請求url地址 url = 'https://www.chinawenwang.com/zlist-55-1.html' # 攜帶請求頭引數 headers 請求頭是字典型別 鍵值對形式 一個關鍵字對應值 中間是用:隔開的 # User-Agent 瀏覽器的基本資訊 # 請求頭是為了把python代碼偽裝成瀏覽器對于服務器發送請求 (披著羊皮狼) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36' } # 請求方式: 常見 get請求 post請求 response = requests.get(url=url, headers=headers) # <Response [200]> response回應物件 <> 200 狀態碼 表示請求成功 # 獲取的是回應體的文本資料 (亂碼) 轉碼
2. 獲取資料, 獲取網頁源代碼 response.text (html字串資料內容)
print(response.text)
3. 決議資料, 提取文章url地址或者文章標題
# 決議資料方法: re正則運算式[可以直接匹配字串資料內容] css選擇器 xpath (對于html字串資料進行資料轉換) # 如果你是想要從事相關作業 招聘需求有一個要求 re css xpath 都要會 selector = parsel.Selector(response.text) # 把html字串資料進行資料轉換 selector 物件 # attr(href) 屬性選擇器 獲取a標簽里面的href屬性 css語法 在VIP課程都一節課內容 (2.5小時內容) # getall() 獲取所有 回傳串列 匹配多個資料 都是回傳串列 href = https://www.cnblogs.com/qshhl/archive/2021/09/16/selector.css('.d-flex h2 a::attr(href)').getall()[:-2]
4. 發送請求, 對于文章詳情頁url地址發送請求
for index in href: response_1 = requests.get(url=index, headers=headers)
5. 獲取資料, 獲取網頁源代碼
print(response_1.text)
6. 決議資料, 提取文章內容
selector_1 = parsel.Selector(response_1.text)
獲取文章標題 get() 獲取一個 回傳的字串資料
title = selector_1.css('.content-page-header-div h1::text').get() content = selector_1.css('.content-page-main-content-div').get() html_content = html_str.format(article=content)
7. 保存資料, 保存成html檔案內容
# 檔案路徑以及檔案名后綴 html_path = html_filename + title + '.html' pdf_path = pdf_filename + title + '.pdf' with open(html_path, mode='w', encoding='utf-8') as f: f.write(html_content)
8. 保存PDF, 需要把html檔案轉成PDF檔案內容
# 配置軟體 指定軟體位置 config = pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe') # 把html檔案里面的內容 轉成pdf 保存到 pdf檔案夾 pdfkit.from_file(html_path, pdf_path, configuration=config) print('正在保存: ', title)
對于本篇文章有疑問的同學也可以點這里

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