import csv
import time
import requests
import re # 正则表达式 内置模块,不用安装
import json
import pprint # 可视化输出 按照一定格式输出
f = open('51job.csv',mode='a',encoding='ANSI',newline='')
csv_writer = csv.DictWriter(f,fieldnames=['职位信息','城市','基本信息','学历要求','公司名称','公司类型','公司规模','公司性质','公司福利','职位薪资','发布日期','职位详情'])
csv_writer.writeheader() # 写入表头
for page in range(1,10):
# 1.发送请求
url = f'https://search.51job.com/list/000000,000000,0000,00,9,99,python,2,{page}.html?lang=c&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare='
time.sleep(20)
# 构建请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0.1293.47'
}
response = requests.get(url = url,headers=headers)
# 2.获取数据 获取响应体文本数据 response.text
# 动态网页 response.json()获取json字典数据
# 保存下载图片 视频 音频 获取响应体二进制数据 response.content
# print(response.text)
# 3.解析数据
# json数据直接解析 re正则表达式 css选择器 xpath
# () 精确匹配 匹配括号内想要的内容 去头window.__SEARCH_RESULT__ = 去尾 </script> 只要中间(.*?)
# findall 查找所有 从response.text当中匹配
html_data = re.findall('window\.__SEARCH_RESULT__ = (.*?)</script>',response.text)[0]
# print(html_data) # 正则表达式提取出的内容返回的是列表
# 把字符串数据转成json字典数据
json_data = json.loads(html_data)
# 格式化输出 使用pprint模块调用pprint方法
# pprint.pprint(json_data)
# 解析json数据,和字典取值相同,根据键值对取值,冒号左边的内容(键) 提取 冒号右边的内容(值)
search_result = json_data['engine_jds']
# for遍历 提取search_result列表中的每一个元素
for index in search_result :
# pprint.pprint(index)
# break
title = index['job_name'] # 职位名称
city = index['workarea_text']
attribute_text = index['attribute_text'] # 基本信息
degree = attribute_text[-1]
# 列表转字符串
job_info = '|'.join(attribute_text) # | 采用| 隔开
company_name = index['company_name']
company_text = index['companyind_text']
company_size_text = index['companysize_text']
company_type_text = index['companytype_text']
job_welf = index['jobwelf']
providesalary_text = index['providesalary_text']
updatedate = index['updatedate']
job_href = index['job_href']
dit = {
'职位信息' : title,
'城市' : city,
'基本信息' : attribute_text,
'学历要求' : degree,
'公司名称' : company_name,
'公司类型' : company_text,
'公司规模': company_size_text,
'公司性质': company_type_text,
'公司福利': job_welf,
'职位薪资': providesalary_text,
'发布日期': updatedate,
'职位详情': job_href
}
print(dit)
csv_writer.writerow(dit)
Python_51job案例分析
于 2022-08-12 20:45:16 首次发布