对于每个上班族来说,总要经历几次换工作,如何在网上挑到心仪的工作?如何提前为心仪工作的面试做准备?今天我们来抓取智联招聘的招聘信息,助你换工作成功!
运行平台: Windows
Python版本: Python3.6
IDE: Sublime Text
其他工具: Chrome浏览器
以北京海淀区的python工程师为例进行网页分析。打开智联招聘首页,选择北京地区,在搜索框输入"python工程师",点击"搜工作":
1搜索职位
接下来跳转到搜索结果页面,按"F12"打开开发者工具,然后在"热门地区"栏选择"海淀",我们看一下地址栏:
2选择地区
由地址栏后半部分searchresult.ashx?jl=北京&kw=python工程师&sm=0&isfilter=1&p=1&re=2005可以看出,我们要自己构造地址了。接下来要对开发者工具进行分析,按照如图所示步骤找到我们需要的数据:Request Headers和Query String Parameters :
3开发者工具分析
构造请求地址:
paras = { 'jl': '北京', # 搜索城市
'kw': 'python工程师', # 搜索关键词
'isadv': 0, # 是否打开更详细搜索选项
'isfilter': 1, # 是否对结果过滤
'p': 1, # 页数
're': 2005 # region的缩写,地区,2005代表海淀}
url = 'https://sou.zhaopin.com/jobs/searchresult.ashx?' + urlencode(paras)请求头:
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', 'Host': 'sou.zhaopin.com', 'Referer': 'https://www.zhaopin.com/', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,**;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9'
}
url = 'https://sou.zhaopin.com/jobs/searchresult.ashx?' + urlencode(paras) try: # 获取网页内容,返回html数据
response = requests.get(url, headers=headers) # 通过状态码判断是否获取成功
if response.status_code == 200: return response.text return None
except RequestException as e: return Nonedef parse_one_page(html):
'''
解析HTML代码,提取有用信息并返回
'''
# 正则表达式进行解析
pattern = re.compile('(.*?).*?' # 匹配职位信息
'(.*?).*?' # 匹配公司网址和公司名称
' (.*?) ', re.S) # 匹配月薪
# 匹配所有符合条件的内容
items = re.findall(pattern, html)
for item in items:
job_name = item[0]
job_name = job_name.replace('', '')
job_name = job_name.replace('', '') yield { 'job': job_name, 'website': item[1], 'company': item[2], 'salary': item[3]
}def write_csv_file(path, headers, rows):
'''
将表头和行写入csv文件
'''
# 加入encoding防止中文写入报错
# newline参数防止每写入一行都多一个空行
with open(path, 'a', encoding='gb18030', newline='') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)def write_csv_headers(path, headers):
'''
写入表头
'''
with open(path, 'a', encoding='gb18030', newline='') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()def write_csv_rows(path, headers, rows):
'''
写入行
'''
with open(path, 'a', encoding='gb18030', newline='') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writerows(rows)def main(city, keyword, region, pages):
'''
主函数
'''
filename = 'zl_' + city + '_' + keyword + '.csv'
headers = ['job', 'website', 'company', 'salary']
write_csv_headers(filename, headers) for i in tqdm(range(pages)): '''
获取该页中所有职位信息,写入csv文件
'''
jobs = []
html = get_one_page(city, keyword, region, i)
items = parse_one_page(html) for item in items:
jobs.append(item)
write_csv_rows(filename, headers, jobs)if __name__ == '__main__':
main('北京', 'python工程师', 2005, 10)上面代码执行效果如图所示:
8代码执行效果
执行完成后会在py同级文件夹下会生成名为:zl_北京_python工程师.csv的文件,打开之后效果如下:
9数据保存结果
本示例功能比较简单,只做到了数据抓取,并没有对数据分析,下次我会抓取更多信息,对薪水和职位对工作技能的要求等各项数据进行分析,敬请期待!
作者:瑶曳风尘
链接:https://www.jianshu.com/p/50d8640fcf1e



