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