Python爬蟲抓取智聯(lián)招聘(基礎(chǔ)版)
對于每個上班族來說,總要經(jīng)歷幾次換工作,如何在網(wǎng)上挑到心儀的工作?如何提前為心儀工作的面試做準(zhǔn)備?今天我們來抓取智聯(lián)招聘的招聘信息,助你換工作成功!
運行平臺: Windows
Python版本: Python3.6
IDE: Sublime Text
其他工具: Chrome瀏覽器
1、網(wǎng)頁分析
1.1 分析請求地址
以北京海淀區(qū)的python工程師為例進(jìn)行網(wǎng)頁分析。打開智聯(lián)招聘首頁,選擇北京地區(qū),在搜索框輸入"python工程師",點擊"搜工作":
接下來跳轉(zhuǎn)到搜索結(jié)果頁面,按"F12"打開開發(fā)者工具,然后在"熱門地區(qū)"欄選擇"海淀",我們看一下地址欄:
由地址欄后半部分searchresult.ashx?jl=北京&kw=python工程師&sm=0&isfilter=1&p=1&re=2005可以看出,我們要自己構(gòu)造地址了。接下來要對開發(fā)者工具進(jìn)行分析,按照如圖所示步驟找到我們需要的數(shù)據(jù):Request Headers和Query String Parameters :
構(gòu)造請求地址:
- paras = {
- 'jl': '北京', # 搜索城市
- 'kw': 'python工程師', # 搜索關(guān)鍵詞
- 'isadv': 0, # 是否打開更詳細(xì)搜索選項
- 'isfilter': 1, # 是否對結(jié)果過濾
- 'p': 1, # 頁數(shù)
- 're': 2005 # region的縮寫,地區(qū),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'
- }
1.2 分析有用數(shù)據(jù)
接下來我們要分析有用數(shù)據(jù),從搜索結(jié)果中我們需要的數(shù)據(jù)有:職位名稱、公司名稱、公司詳情頁地址、職位月薪:
通過網(wǎng)頁元素定位找到這幾項在HTML文件中的位置,如下圖所示:
用正則表達(dá)式對這四項內(nèi)容進(jìn)行提?。?nbsp;
- # 正則表達(dá)式進(jìn)行解析
- pattern = re.compile('<a style=.*? target="_blank">(.*?)</a>.*?' # 匹配職位信息
- '<td class="gsmc"><a href="(.*?)" target="_blank">(.*?)</a>.*?' # 匹配公司網(wǎng)址和公司名稱
- '<td class="zwyx">(.*?)</td>', re.S) # 匹配月薪
- # 匹配所有符合條件的內(nèi)容
- items = re.findall(pattern, html)
注意:解析出來的部分職位名稱帶有標(biāo)簽,如下圖所示:
那么在解析之后要對該數(shù)據(jù)進(jìn)行處理剔除標(biāo)簽,用如下代碼實現(xiàn):
- for item in items:
- job_name = item[0]
- job_name = job_name.replace('<b>', '')
- job_name = job_name.replace('</b>', '')
- yield {
- 'job': job_name,
- 'website': item[1],
- 'company': item[2],
- 'salary': item[3]
- }
2、寫入文件
我們獲取到的數(shù)據(jù)每個職位的信息項都相同,可以寫到數(shù)據(jù)庫中,但是本文選擇了csv文件,以下為百度百科解釋:
逗號分隔值(Comma-Separated Values,CSV,有時也稱為字符分隔值,因為分隔字符也可以不是逗號),其文件以純文本形式存儲表格數(shù)據(jù)(數(shù)字和文本)。純文本意味著該文件是一個字符序列,不含必須像二進(jìn)制數(shù)字那樣被解讀的數(shù)據(jù)。
由于python內(nèi)置了csv文件操作的庫函數(shù),所以很方便:
- import csv
- 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)
3、進(jìn)度顯示
要想找到理想工作,一定要對更多的職位進(jìn)行篩選,那么我們抓取的數(shù)據(jù)量一定很大,幾十頁、幾百頁甚至幾千頁,那么我們要掌握抓取進(jìn)度心里才能更加踏實啊,所以要加入進(jìn)度條顯示功能。
本文選擇tqdm 進(jìn)行進(jìn)度顯示,來看一下酷炫結(jié)果(圖片來源網(wǎng)絡(luò)):
執(zhí)行以下命令進(jìn)行安裝:pip install tqdm。
簡單示例:
- from tqdm import tqdm
- from time import sleep
- for i in tqdm(range(1000)):
- sleep(0.01)
4、完整代碼
以上是所有功能的分析,如下為完整代碼:
- #-*- coding: utf-8 -*-
- import re
- import csv
- import requests
- from tqdm import tqdm
- from urllib.parse import urlencode
- from requests.exceptions import RequestException
- def get_one_page(city, keyword, region, page):
- '''
- 獲取網(wǎng)頁html內(nèi)容并返回
- '''
- paras = {
- 'jl': city, # 搜索城市
- 'kw': keyword, # 搜索關(guān)鍵詞
- 'isadv': 0, # 是否打開更詳細(xì)搜索選項
- 'isfilter': 1, # 是否對結(jié)果過濾
- 'p': page, # 頁數(shù)
- 're': region # region的縮寫,地區(qū),2005代表海淀
- }
- 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:
- # 獲取網(wǎng)頁內(nèi)容,返回html數(shù)據(jù)
- response = requests.get(url, headers=headers)
- # 通過狀態(tài)碼判斷是否獲取成功
- if response.status_code == 200:
- return response.text
- return None
- except RequestException as e:
- return None
- def parse_one_page(html):
- '''
- 解析HTML代碼,提取有用信息并返回
- '''
- # 正則表達(dá)式進(jìn)行解析
- pattern = re.compile('<a style=.*? target="_blank">(.*?)</a>.*?' # 匹配職位信息
- '<td class="gsmc"><a href="(.*?)" target="_blank">(.*?)</a>.*?' # 匹配公司網(wǎng)址和公司名稱
- '<td class="zwyx">(.*?)</td>', re.S) # 匹配月薪
- # 匹配所有符合條件的內(nèi)容
- items = re.findall(pattern, html)
- for item in items:
- job_name = item[0]
- job_name = job_name.replace('<b>', '')
- job_name = job_name.replace('</b>', '')
- yield {
- 'job': job_name,
- 'website': item[1],
- 'company': item[2],
- 'salary': item[3]
- }
- def write_csv_file(path, headers, rows):
- '''
- 將表頭和行寫入csv文件
- '''
- # 加入encoding防止中文寫入報錯
- # newline參數(shù)防止每寫入一行都多一個空行
- 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):
- '''
- 主函數(shù)
- '''
- 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)
上面代碼執(zhí)行效果如圖所示:
執(zhí)行完成后會在py同級文件夾下會生成名為:zl_北京_python工程師.csv的文件,打開之后效果如下: