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

python爬取拉勾网出现KeyError: ‘content’

在爬取拉勾网的时候,出现如下报错,经分析解析路径没有出错,是cookie过期,没有响应数据,即不存在这个数据,才会出现如下报错:
在这里插入图片描述

【解决办法】

1、 设置条件语句:

import requests
import json

def main():
    for i in range(1,3):
        url = 'https://www.lagou.com/jobs/positionAjax.json?'
        data = {
            'first': 'false',
            'pn': i,
            'kd': '爬虫',
        }
        head = {
            'Referer': 'https://www.lagou.com/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.net/August1226/article/details/80654911

  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值