python爬取拉勾网出现KeyError: ‘content’
在爬取拉勾网的时候,出现如下报错,经分析解析路径没有出错,是cookie过期,没有响应数据,即不存在这个数据,才会出现如下报错:
【解决办法】
1、 设置条件语句:
import requests
import json
def main():
for i in range(1,3):
url = 'https://www.lagou/jobs/positionAjax.json?'
data = {
'first': 'false',
'pn': i,
'kd': '爬虫',
}
head = {
'Referer': 'https://www.lagou/jobs/list_%E7%88%AC%E8%99%AB?labelWords=&fromSearch=true&suginput=',
'Cookie': '***', # 自己实时补上
'User-Agent': 'Mozilla/5.0 ' # 自己实时补上
}
response = requests.post(url,headers=head,data=data )
# print(response.json())
response = response.json()
if 'content' in response:
for content in response['content']['positionResult']['result']:
company = content.get('positionName')
creatime = content.get('createTime')
print(company, creatime)
else:
print('not exist')
main()
2)运用get()
利用dict内置的get(key,default)方法,如果key存在,则返回其value,否则返回default;使用这个方法永远不会触发Key Error.
print(a.get('gender'))
print(a.get('gender','不存在!'))
print(a.get('name','不存在!'))
参考:https://blog.csdn/August1226/article/details/80654911
更多推荐
python爬取拉勾网出现KeyError: 'content'
发布评论