啊哈,自己太懶了,招聘信息什么的懶的看了寨躁,索性抓取下來(lái)慢慢看。
1. 我為什么要爬取招聘信息
其實(shí)我就是太懶了牙勘,雖然我是個(gè)做Android的职恳,但是擋不住我使用Python的熱情。
2. 如何實(shí)現(xiàn)
懶得說(shuō)了方面,你自己看代碼吧放钦。
2.0 一些說(shuō)明
1. 為什么需要Cookie
按照現(xiàn)在網(wǎng)站的尿性,沒(méi)有Cookie恭金,你什么信息也拿不到最筒。
所以老實(shí)的登錄吧,然后使用自己的Cookie蔚叨,反正我的Cookie是不會(huì)給你用的床蜘。
2. 如何獲取網(wǎng)頁(yè)URL
我覺(jué)得這個(gè)問(wèn)題太簡(jiǎn)單了,我拒絕回答蔑水!
哈哈邢锯,Chrome啊等瀏覽器自帶的開(kāi)發(fā)工具,足夠分析使用了搀别。
3. 嚴(yán)重警告
代碼寫(xiě)的一般丹擎,大家隨便看看就好,想用的自己去改造歇父。
2.1 LagouSpider
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Date: 2018-12-04 09:56:28
from bs4 import BeautifulSoup
from urllib import request, parse
import os
import json
from Utils import CsvWriter
class LagouSpider:
'''
抓取拉勾上的招聘信息蒂培。
因?yàn)橄拗频脑颍仨氁竽愕卿涀约旱馁~號(hào)后榜苫,截取所需的Cookie护戳。
'''
def __init__(self, url):
self.page_header = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Host': 'www.lagou.com',
'Origin': 'https://www.lagou.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
'Connection': 'keep-alive',
'Referer': 'https://www.lagou.com/jobs/list_Android?labelWords=&fromSearch=true&suginput=',
'X-Anit-Forge-Token': 'None',
'X-Requested-With': 'XMLHttpRequest',
'Cookie': '填寫(xiě)你登錄拉勾網(wǎng)后的Cookie信息'
}
self.url = url
self.tags = [('positionId', '職位ID'), ('positionName', '職位名稱(chēng)'), ('salary', '薪資'), ('createTime', '發(fā)布時(shí)間'), ('workYear', '工作經(jīng)驗(yàn)'), ('education', '學(xué)歷'), ('positionLables', '職位標(biāo)簽'), ('jobNature', '職位類(lèi)型'), ('firstType', '職位大類(lèi)'), ('secondType', '職位細(xì)類(lèi)'), ('positionAdvantage', '職位優(yōu)勢(shì)'), ('city', '城市'),
('district', '行政區(qū)'), ('businessZones', '商圈'), ('publisherId', '發(fā)布人ID'), ('companyId', '公司ID'), ('companyFullName', '公司名'), ('companyShortName', '公司簡(jiǎn)稱(chēng)'), ('companyLabelList', '公司標(biāo)簽'), ('companySize', '公司規(guī)模'), ('financeStage', '融資階段'), ('industryField', '企業(yè)領(lǐng)域'), ('industryLables', '企業(yè)標(biāo)簽')]
def fetch_page_info(self, page_num, keyword, file_path):
'''
根據(jù)url來(lái)獲取網(wǎng)頁(yè)內(nèi)容。
page_num:頁(yè)數(shù)垂睬。
keyword:關(guān)鍵字
file_path:寫(xiě)入文件的路徑媳荒,要求必須為csv文件。
'''
if self.url is None:
print('Url為空驹饺,無(wú)法獲取信息钳枕。')
return
file_name = os.path.basename(file_path)
if not file_name.endswith('csv'):
print("請(qǐng)使用csv文件來(lái)記錄信息。")
return
if not keyword.strip():
print("關(guān)鍵字不能為空赏壹。")
return
page_data = parse.urlencode(
[('pn', page_num), ('kd', keyword)])
req = request.Request(self.url, headers=self.page_header)
page = request.urlopen(req, data=page_data.encode('utf-8')).read()
page = page.decode('utf-8')
print('Get content is:{}'.format(page))
if page is None:
print('Text is Null.')
return
data = json.loads(page)
postionResult = data.get('content').get('positionResult').get('result')
# 將數(shù)據(jù)記錄至CSV中
# 首先寫(xiě)入頭
headers = []
for tag in self.tags:
headers.append(tag[1])
rows = []
rows.append(headers)
for position in postionResult:
row = []
for tag in self.tags:
row.append(position.get(tag[0]))
rows.append(row)
CsvWriter.writeRows(filePath=file_path, rows=rows)
# # 將數(shù)據(jù)寫(xiě)入文件中
# with open('Position.txt', 'w+') as f:
# for position in postionResult:
# f.write("---------------------------\n")
# for tag in tags:
# f.write(str(tag[1])+":"+str(position.get(tag[0]))+"\n")
# print("解析完畢鱼炒。")
if __name__ == '__main__':
url = r'https://www.lagou.com/jobs/positionAjax.json?city=%E4%B8%8A%E6%B5%B7'
spider = LagouSpider(url)
filePath = os.path.dirname(__file__)+os.sep+'Position_Patch.csv'
for index in range(1,9):
spider.fetch_page_info(
page_num=index, keyword='Android', file_path=filePath)
print("解析完成,請(qǐng)查看文件蝌借。")
2.2 Utils
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Date: 2018-12-04 14:21:39
import csv
class CsvWriter:
@staticmethod
def writeRow(filePath, row):
with open(filePath, newline='', mode='a') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(row)
@staticmethod
def writeRows(filePath, rows):
print(len(rows))
with open(filePath, newline='', mode='a') as f:
csv_writer = csv.writer(f)
csv_writer.writerows(rows)
class CsvReader:
@staticmethod
def printRows(filePath):
with open(filePath, 'r+') as f:
reader = csv.reader(f)
for row in reader:
print(row)
3. 總結(jié)
我注釋寫(xiě)的那么詳細(xì)昔瞧,如果存在疑問(wèn)俐巴,歡迎留言。