python3 利用requests爬取拉勾網資料
阿新 • • 發佈:2019-01-10
學習python,瞭解了一點爬蟲的知識,成功的對拉勾網的招聘資訊進行了爬取,將爬取心得記錄下來,和大家一起學習進步。
準備工作:
python3
requests
pandas
谷歌瀏覽器(或者火狐瀏覽器、qq瀏覽器)
爬取步驟:
首先開啟拉勾網的網址對網站進行分析,開啟拉勾網首頁(https://www.lagou.com/),通過常用的get方式請求,返回的網頁資訊不完整,考慮網站是用了ajax非同步重新整理,所以需要用開發者工具,擷取資料包,找到post請求的頁面,進行分析。
按照圖片中的箭頭所示,先開啟f12除錯工具,點選Network,然後輸入你想搜尋的職位名稱,在這以python為例,搜尋,會看見下面加載出很多的檔案,在這裡選擇XHR格式,第一個就是post請求的檔案,這是我們開始分析這個post請求,看看是不是我們所需要的頁面
發現裡面儲存的是我們需要的資料,隨意需要使用post請求,獲取動態載入的資料
上面的是我們需要的模仿瀏覽器訪問新增的請求頭,下面的是我們通過post提交的資料
首先我們需要安裝requests和pandas模組,
可以使用
pip install requests
pip install pandas
安裝模組
然後開始程式碼實現:
import requests
from time import sleep
import random
import pandas
#職位所屬地
city='北京'
#職位關鍵字
job='python'
url='https://www.lagou.com/jobs/positionAjax.json?city=' +city+'&needAddtionalResult=false&isSchoolJob=0'
header = {
'Host': 'www.lagou.com',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'zh-CN,en-US;q=0.7,en;q=0.3' ,
'Accept-Encoding': 'gzip, deflate, br',
'Referer': 'https://www.lagou.com/jobs/list_Python?labelWords=&fromSearch=true&suginput=',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'X-Anit-Forge-Token': 'None',
'X-Anit-Forge-Code': '0',
'Content-Length': '26',
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache'
}
for num in range(1,16):
#取隨機延遲
ran=random.randint(1,3)
sleep(ran)
#
flag='true'
if num!=1:
flag='false'
form = {'first':flag,
'kd':job,
'pn':str(num)}
html=requests.post(url=url,data=form,headers=header)
result=html.json()
print('--------------------'+str(num)+'-----------------------')
data=result['content']['positionResult']['result']
print(data)
table = pandas.DataFrame(data)
table.to_csv(r'C:\Users\Administrator\Desktop\LaGouPython.csv',header = False, index = False,mode='a+')
經過一段時間的等待,可以在桌面看到我們爬取的全部拉勾網的資訊
以上簡單的爬蟲就已經實現了,歡迎大家一起學習交流。