Crossin的编程教室

标题: 查天气(3)疑问请教 [打印本页]

作者: shixiao4236806    时间: 2018-9-4 18:17
标题: 查天气(3)疑问请教
如下代码,跟公众号里代码类似,content能打印出来,但是data打印就会报错。请问是哪里出了问题??
代码如下:
import urllib.request
import json
from city import city   #前一个是模块名,自定义模块。后一个是变量名

print("你想要查询的城市")
one_city=input("请输入:")
citycode=city.get(one_city)
if citycode:
    web=urllib.request.urlopen("http://www.weather.com.cn/data/cityinfo/%s.html"%citycode)
    content=web.read()
    print(content)
    data=json.loads(content)
    print(data)

run之后,报错如下:
=== RESTART: C:/Users/MyPC/AppData/Local/Programs/Python/Python36/查天气1.py ===
你想要查询的城市是
请输入:北京
b'{"weatherinfo":{"city":"\xe5\x8c\x97\xe4\xba\xac","cityid":"101010100","temp1":"18\xe2\x84\x83","temp2":"31\xe2\x84\x83","weather":"\xe5\xa4\x9a\xe4\xba\x91\xe8\xbd\xac\xe9\x98\xb4","img1":"n1.gif","img2":"d2.gif","ptime":"18:00"}}'
Traceback (most recent call last):
  File "C:/Users/MyPC/AppData/Local/Programs/Python/Python36/查天气1.py", line 13, in <module>
    data=json.loads(content)
  File "C:\Users\MyPC\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
>>>



作者: shixiao4236806    时间: 2018-9-5 18:12
在代码
print(content)
后面加一行,转换成str即可。
content = content.decode('utf8')

问题已解。。




欢迎光临 Crossin的编程教室 (https://bbs.crossincode.com/) Powered by Discuz! X2.5