《Python从入门到实践》第17章对GitHub最受欢迎的python仓库排名用pygal可视化(python_repos.py)报错原因及解决

本文详细解析了在使用Python爬取GitHub仓库信息时遇到的UnicodeEncodeError错误,并提供了有效的解决方案。通过调整代码中对描述字段的处理方式,成功避免了因特殊字符导致的编码问题,确保程序稳定运行。

书中第349页运行python_repos.py报如下错误:

AttributeError: 'NoneType' object has no attribute 'decode'

对仓库们进行id和description打印,查看一下哪里出了问题:

import requests

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)

response_dict = r.json()
print("Total repositories:", response_dict['total_count'])

repositories = response_dict['items']
for i in repositories:
    print('id:',i['id'],'\nDescription:',i['description'])

程序运行后对仓库的id和description依次进行打印:
在这里插入图片描述
可以看到id为3544424的Description有问题,显示报错UnicodeEncodeError.
去API调用(https://api.github.com/search/repositories?q=language:python&sort=stars)看一下这个仓库的描述是这个样子的:
在这里插入图片描述
这个httpie的描述有一个🥧就是不能转码的原因。
之前看到别人说的如果Description是空值(None)也会报错,我现在看的这个排名里的仓库恰好没有空值。
解决:
在plot_dict这个字典里,description用str()转换成字符串:

plot_dict = {
			'value':i['stargazers_count'],
            'label':str(i['description']),
            }

然后就可以顺利出图啦!鼠标放到条形时显示的项目描述还是会正常显示🥧的!

小小扩展:
刚刚那个检查的代码遇到第一个不能打印的描述时就停止了,可以用try-except来看看所有不能正常打印的描述:

import requests

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)

response_dict = r.json()
print("Total repositories:", response_dict['total_count'])

repositories = response_dict['items']
for i in repositories:
    try:
        print('id:',i['id'],'\nDescription:',i['description'])
    except UnicodeEncodeError:
        print('CANNOT PRINT DESCRIPTION')

凡是有不能转码的描述都会打印CANNOT PRINT DESCRIPTION

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值