本次內容:
Python采集某網站數據內容, 并把詳情信息保存PDF
本次使用開發環境:
- Python 3.8
- Pycharm 2021.2專業版
- 保存PDF 需要 wkhtmltopdf 安裝包
模塊使用:
需安裝模塊
- requests 數據請求模塊
安裝方法:pip install requests - parsel 數據解析模塊 pip install parsel
- pdfkit PDF模塊 pip install pdfkit
內置模塊(不許安裝)
- re 正則表達式 內置模塊
- json 字符串轉Json數據 內置模塊
- csv 保存csv模塊 內置模塊
- time 時間模塊 內置模塊
如何安裝模塊
- win + R 輸入 cmd 點擊確定, 輸入安裝命令 pip install 模塊名 (pip install requests) 回車
- 在pycharm中點擊Terminal(終端) 輸入安裝命令
本節課的案例思路(爬蟲最基本思路流程):
一. 數據來源分析
- 確定我們想要數據內容是什么? 音樂
- 通過開發者工具進行抓包分析, 分析數據來源 >>> 音樂播放地址是從哪里的
二. 代碼實現步驟 爬蟲四部曲: 發送請求 >>> 獲取數據 >>> 解析數據 >>> 保存數據
- 發送請求, 對于什么url發送什么請求, 攜帶headers偽裝
網址
發送請求get請求 - 獲取數據, 獲取服務器返回響應數據
- 解析數據, 提取我們想要數據內容 職位相關信息數據
- 保存數據, 保存文本/數據庫/表格.... csv表格數據
- 多頁數據采集
代碼展示
首先導入模塊
import requests
import parsel # 數據解析模塊 pip install parsel
import pdfkit # pip install pdfkit
# 導入正則表達式模塊
import re # 內置模塊
# 導入json
import json # 內置模塊
# 導入格式化輸出模塊
import pprint # 內置模塊
# 導入csv模塊
import csv # 內置模塊
# 導入時間模塊
import time
1. 發送請求
def get_job_content(title, html_url):
# url = 'https://jobs.51job.com/shenzhen-lgq/138509815.html' # 招聘詳情頁
html_str = """
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
{article}
</body>
</html>
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
}
response = requests.get(url=html_url, headers=headers, proxies=[])
response.encoding = 'gbk'
2. 獲取數據
# print(response.text)
3. 解析數據 css選擇器 根據標簽屬性提取數據內容
selectors = parsel.Selector(response.text) # 把獲取到html字符串數據轉成selector對象
content = selectors.css('body > div.tCompanyPage > div.tCompany_center.clearfix > div.tCompany_main').get()
print(content)
html_data = html_str.format(article=content)
# '1.html' 公司名字 + 職位名字 命名
html_path = 'html\\' + title + '.html'
pdf_path = 'pdf\\' + title + '.pdf'
with open(html_path, mode='w', encoding='utf-8') as f:
f.write(html_data)
config = pdfkit.configuration(wkhtmltopdf=r'C:\01-Software-installation\wkhtmltopdf\bin\wkhtmltopdf.exe')
pdfkit.from_file(html_path, pdf_path, configuration=config)
# mode模式保存方式/讀取方式 a追加寫入 不會覆蓋 w 寫入 會覆蓋
f = open('招聘_1.csv', mode='a', encoding='utf-8', newline='')
csv_writer = csv.DictWriter(f, fieldnames=[
'標題',
'公司名字',
'薪資',
'城市',
'學歷',
'經驗',
'公司類型',
'公司屬性',
'公司規模',
'福利待遇',
'發布日期',
'詳情頁',
])
csv_writer.writeheader() # 寫入表頭
for page in range(1, 11):
1. 發送請求 f'{page}' 字符串格式化方法 format()
print(f'===============================正在采集第{page}頁的數據內容===============================')
time.sleep(2)
url = f'https://search.51job.com/list/010000%252c020000%252c030200%252c040000,000000,0000,00,9,99,python,2,{page}.html'
# headers 字典數據類型 鍵值對形式
# 快速批量替換, 選擇需要替換內容 ctrl + R 輸入 正則語法
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
}
# 通過request模塊里面get方法對于 url地址發送請求, 并且攜帶上headers請求頭, 最后用response自定義變量接收返回數據內容
response = requests.get(url=url, headers=headers)
2. 獲取數據, 獲取服務器返回響應數據
# print(response.text)
3. 解析數據
# 從response.text里面去找尋window.__SEARCH_RESULT__ = (.*?)</script> 從window.__SEARCH_RESULT__ =開始 </script>這里結束中間的
html_data = re.findall('window.__SEARCH_RESULT__ = (.*?)</script>', response.text)[0] # findall() 從哪里找什么數據
# print(html_data)
# type() 可以查看數據類型
# print(type(html_data))
# 如果它是一個字典的話, 對于取值的是會非常方便, 字符串轉字典數據
json_data = json.loads(html_data) # 轉成字典數據類型
# 字典取值 通過鍵值對取值, 通過冒號左邊[鍵]的內容, 提取冒號右邊[值]的內容
# pprint.pprint(json_data['engine_jds']) 格式化輸出 讓字典數據 有一個展開的輸出效果 print()打印是在一行
# lis = [1,2,3,4,5,6,7,9] for i in lis: (for循環遍歷) 把列表里面元素一個一個提取出來
for index in json_data['engine_jds']:
dit = {
'標題': index['job_name'],
'公司名字': index['company_name'],
'薪資': index['providesalary_text'],
'城市': index['workarea_text'],
'學歷': index['attribute_text'][2],
'經驗': index['attribute_text'][1],
'公司類型': index['companytype_text'],
'公司屬性': index['companyind_text'],
'公司規模': index['companysize_text'],
'福利待遇': index['jobwelf'],
'發布日期': index['updatedate'],
'詳情頁': index['job_href'],
}
title = index['job_name'] + index['company_name']
title = re.sub(r'[/\:?*"<>|]', '', title)
get_job_content(title, index['job_href'])
csv_writer.writerow(dit)
print(dit)
一些小知識點
無論是 css xpath 還是 re 正則表達式 提取數據返回是[]空列表
- 語法不對
- 服務器時候返回數據(是否被反爬)
- 是否找對數據來源
xpath-help (匹配是元素面板)
爬蟲是看服務器返回數據
python應用領域
- 爬蟲程序
- 數據分析 >>> 數據分析 powerbi
- 網站開發 >>> 開發一個網站
- 游戲開發 >>> pygame
- 游戲輔助 >>> 模擬點擊 圖像識別 模擬點擊
- 人工智能 >>> 目前算法 都是調用別人寫好API接口
- 圖像處理 >>> 根據照片定位 手機拍照打開定位了 然后發給別人了, 可以通過這張照片定位
- 自動化腳本
- 自動化測試 / 運維
- GUI桌面應用開發 開發軟件 tk pyqt