知識點:
- requests
- css選擇器
- requests >>> pip install requests
- parsel >>> pip install parsel
- pdfkit >>> pip install pdfkit
- 版 本:anaconda5.2.0(python3.6.5)
- 編輯器:pycharm (安裝包/安裝教程/激活碼/使用教程/插件[翻譯插件/主題/漢化包])
- 軟件環境: wkhtmltopdf 把html文件轉成pdf
確定要爬目標: 文檔內容
這些文檔數據內容是可以從哪里獲取的
分析數據的過程:
- 鼠標右鍵點擊檢查或者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
# 請求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 狀態碼 表示請求成功 # 獲取的是響應體的文本數據 (亂碼) 轉碼
print(response.text)
# 解析數據方法: re正則表達式[可以直接匹配字符串數據內容] css選擇器 xpath (對於html字符串數據進行數據轉換) # 如果你是想要從事相關工作 招聘需求有一個要求 re css xpath 都要會 selector = parsel.Selector(response.text) # 把html字符串數據進行數據轉換 selector 對象 # attr(href) 屬性選擇器 獲取a標簽里面的href屬性 css語法 在VIP課程都一節課內容 (2.5小時內容) # getall() 獲取所有 返回列表 匹配多個數據 都是返回列表 href = selector.css('.d-flex h2 a::attr(href)').getall()[:-2]
for index in href: response_1 = requests.get(url=index, headers=headers)
print(response_1.text)
selector_1 = parsel.Selector(response_1.text)
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)
# 文件路徑以及文件名后綴 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)
# 配置軟件 指定軟件位置 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)