Python使用requests出现AttributeError: module ‘collections‘ has no attribute ‘MutableMapping‘

文章讲述了作者在使用PyCharm3.12.0开发Python3.12爬虫时遇到关于`MutableMapping`的错误,通过调整导入方式并更新依赖库解决了问题,强调了使用pip进行包管理的重要性。
摘要由CSDN通过智能技术生成

 我使用的IDE开发工具是PyCharm3.12.0,Python版本是3.12。

第一次学习爬虫时,从网络复制了一段代码如下:

import json
import requests
import xlwt
# 设置头部信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
}
url = "https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js"
response = requests.get(url=url, headers=headers).text
loads = json.loads(response)
dic = loads['hero']

通过PyCharm的setting安装了相应的json,requests,xlwt,安装完成后运行代码,出现了AttributeError: module ‘collections‘ has no attribute ‘MutableMapping‘这样的错误信息,然后网络上的解决方法如下:

from collections import Mapping, MutableMapping 这种用法在 python3.10 上已经被移除了

从 python3.3 开始,就应该使用 from collections.abc import MutableMapping 替代 from collections import Mapping, MutableMapping

于是我在代码里加上:from collections.abc import MutableMapping 

import json
import requests
import xlwt
from collections.abc import MutableMapping
# 设置头部信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
}
url = "https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js"
response = requests.get(url=url, headers=headers).text
loads = json.loads(response)
dic = loads['hero']

运行时发现还是不行。

于是大胆的猜想是不是通过PyCharm安装的requests和json、xlwt版本兼容的问题,把刚刚通过PyCharm安装的requests和json、xlwt卸载掉,重新通过python自带的pip工具安装requests、json、xlwt,果不其然,安装成功之后再运行上面代码就正常运行了。

这个问题给我的警示:后续安装python开发过程需要的包时还是用python自带的安装工具pip更保险些。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值