python爬取拉勾网出现KeyError: 'content'

编程知识 更新时间:2023-04-05 06:25:32

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'

本文发布于:2023-04-05 06:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/d0db33dcce7ce3516d66200883d35ed0.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:爬取拉勾网   python   content   KeyError

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 45266文章数
  • 14阅读数
  • 0评论数