我使用的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更保险些。