|
|
发表于 2017-8-7 14:48:22
|
显示全部楼层
import urllib.request
import json
import pickle
#建立城市字典
pickle_file = open('city_date.pkl', 'rb')
city = pickle.load(pickle_file)
password=input('请输入城市:')
name1=city[password]
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'}
req = urllib.request.Request(url='http://m.weather.com.cn/data/'+name1+'.html',data=None,headers=headers)
# 接着把File那句改成
File1 = urllib.request.urlopen(req)
weatherHTML= File1.read().decode('utf-8')#读入打开的url
weatherJSON = json.JSONDecoder().decode(weatherHTML)#创建json
weatherInfo = weatherJSON['weatherinfo']
#打印信息
print ( '城市:', weatherInfo['city'])
print ('时间:', weatherInfo['date_y'])
print ( '24小时天气:')
print ('温度:', weatherInfo['temp1'])
print ('天气:', weatherInfo['weather1'])
print ('风速:', weatherInfo['wind1'])
print ('紫外线:', weatherInfo['index_uv'])
print ('穿衣指数:', weatherInfo['index_d'])
print ('48小时天气:')
print ('温度:', weatherInfo['temp2'])
print ('天气:', weatherInfo['weather2'])
print ('风速:', weatherInfo['wind2'])
print ('紫外线:', weatherInfo['index48_uv'])
print ('穿衣指数:', weatherInfo['index48_d'])
print ('72小时天气:')
print ('温度:', weatherInfo['temp3'])
print ('天气:', weatherInfo['weather3'])
print ('风速:', weatherInfo['wind3'])
input ('按任意键退出:')
怎么还是这个错误?
Traceback (most recent call last):
File "D:/python/零基础入门学习Python/第7章节/查询天气.py", line 14, in <module>
File1 = urllib.request.urlopen(req)
File "D:\Program Files\Python36\lib\urllib\request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "D:\Program Files\Python36\lib\urllib\request.py", line 532, in open
response = meth(req, response)
File "D:\Program Files\Python36\lib\urllib\request.py", line 642, in http_response
'http', request, response, code, msg, hdrs)
File "D:\Program Files\Python36\lib\urllib\request.py", line 570, in error
return self._call_chain(*args)
File "D:\Program Files\Python36\lib\urllib\request.py", line 504, in _call_chain
result = func(*args)
File "D:\Program Files\Python36\lib\urllib\request.py", line 650, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden |
|