查天气
import requests,json
from city import city
cityname=input(‘你想查看哪个城市的天气?\n’)
你想查看哪个城市的天气?
大连citycode=city.get(cityname)
if citycode:
url = ‘http://www.weather.com.cn/data/cityinfo/%s.html’ % citycode
res=requests.get(url)
content=res.content
content_doc=str(content,‘utf-8’)
print(content_doc.text)
Traceback (most recent call last):
File “<pyshell#5>”, line 6, in
print(content_doc.text)
AttributeError: ‘str’ object has no attribute ‘text’
if citycode:
url = ‘http://www.weather.com.cn/data/cityinfo/%s.html’ % citycode
res=requests.get(url)
content=res.content
print(content.decode(‘utf-8’))
{“weatherinfo”:{“city”:“大连”,“cityid”:“101070201”,“temp1”:“17℃”,“temp2”:“25℃”,“weather”:“多云”,“img1”:“n1.gif”,“img2”:“d1.gif”,“ptime”:“18:00”}}
if citycode:
url = ‘http://www.weather.com.cn/data/cityinfo/%s.html’ % citycode
res=requests.get(url)
content=res.content
data=json.loads(content.decode(‘utf-8’))
result=data[‘weatherinfo’]
str_temp=(’%s\n%s~%s’)%(result[‘weather’],result[‘temp1’],result[‘temp2’])
print(str_temp)