如下是我簡單的獲取拉鉤網(wǎng)異步加載頁面信息的過程
獲取的是深圳 Python 崗位的所有信息馒索,并保存在Mongo中
(對于異步加載曹体,有的人說是把你要爬頁面的信息整個頁面先爬下來色瘩,保存本地单绑,然后再看有沒有你要的東西嘱函,有不是異步币厕,沒有就是異步列另;這種方式當(dāng)然是沒有任何問題,但是我的判斷方式是旦装,當(dāng)我點擊頁面某個位置時页衙,頁面的鏈接并沒有變化,而內(nèi)容卻發(fā)生了變化阴绢,這種我就說它是異步加載店乐,當(dāng)然,異步加載方式很多呻袭,我們要具體網(wǎng)站具體分析)
這個東西完全可以封裝成類眨八,各司其職(這里就可以延伸到Scrapy框架) 后面會更新一個使用Scrapy框架抓取信息的教程
當(dāng)然還有selenium+phantomjs
直接上代碼
import requests
import json
import pymongo
headers = {
'Referer':'https://www.lagou.com/jobs/list_Python?px=default&city=%E6%B7%B1%E5%9C%B3',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0'}
# headers中的Referer參數(shù)是必須的,左电?號之前都是必須的后面可以省略廉侧,不會對結(jié)果有影響
pagenum = 1
key = 'Python' #這里可以設(shè)置一個列表页响,先抓取頁面所有的技術(shù)名稱,保存起來段誊,然后抓取職位信息的時候循環(huán)嵌套遍歷
first = 'true'#可以不要闰蚕,沒發(fā)現(xiàn)有什么作用
post_data = {'first': first,'kd':key,'pn':pagenum}
#first:代表是不是首頁,kd:代表關(guān)鍵字连舍,pn:代表第幾頁
json_url = 'https://www.lagou.com/jobs/positionAjax.json?px=default&city=%E6%B7%B1%E5%9C%B3&needAddtionalResult=false&isSchoolJob=0'
#獲取json內(nèi)容
def get_content(post_data):
r = requests.post(json_url,headers=headers,data=post_data)
datas = json.loads(r.text)
return datas['content']
#獲取mongo連接
def get_connect():
client = pymongo.MongoClient('localhost', 27017)
lagou = client['panpan']
lagoudt = lagou['lagou']
return lagoudt
#數(shù)據(jù)寫入數(shù)據(jù)庫
def to_mongo(results):
lagou = get_connect()
for result in results:
lagou.insert(
{'positionName' : result['positionName'],
'positionLibles' : ','.join(result['positionLables']),
'workYear' : result['workYear'],
'education': result['education'],
'salary' : result['salary'],
'city' : result['city'],
'financeStage' : result['financeStage'],
'industryField' : result['industryField'],
'createTime' : result['createTime'],
'positionAdvantage' : result['positionAdvantage'],
'companySize' : result['companySize'],
'district' : result['district'],
'companyShortName' : result['companyShortName'],
'companyFullName' : result['companyFullName'],
'firstType' : result['firstType'],
'secondType' : result['secondType'],
'subwayline' : result['subwayline'],
'stationname' : result['stationname'],
'linestaion' : result['linestaion']})
total_page = get_content(post_data)['pageSize'] #總頁數(shù)
#循環(huán)每一頁的內(nèi)容
for page in range(1,total_page+1):
first = 'false'
print(page)#記錄當(dāng)前頁碼
post_data = {'kd':'Python','pn':page}
data = get_content(post_data)
to_mongo(data['positionResult']['result'])
這明細(xì)是一個異步加載的例子没陡,我就不多說了,前面有
圖片.png
這個一看就是通過Ajax 實現(xiàn)的異步加載嗎索赏,而且Response里返回的JSon內(nèi)容就是我們需要的呀盼玄,直接取不就行了,話不多說参滴,直接看上面代碼强岸,有疑問的可以給我留言锻弓,我也是剛開始學(xué)砾赔,有問題的地方,請您指正
圖片.png