使用 re 和 urllib.request 模块



im 使用 Python 3.7,我想编写一个以城市命名并返回天气预报的程序。 我用以下代码开始我的代码:

import re
import urllib.request
#https://www.weather-forecast.com/locations/Tel-Aviv-Yafo/forecasts/latest
city=input("entercity:")
url="https://www.weather-forecast.com/locations/" + city +"/forecasts/latest"
data=urllib.request.urlopen(url).read
data1=data.decode("uf-8")
print(data1)

但是当我想读取我的数据时,我收到此错误:

文件 "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py",第 503 行,_call_chain 结果 = func(*args( 文件 "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py",第 649 行,http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp( urllib.error.HTTPError:HTTP 错误 404:未找到 进程已完成,退出代码为 1

=>有人可以帮助我并告诉问题所在吗? 谢谢:(

您输入的城市名称中一定存在拼写错误。我尝试运行以下代码

import re
import urllib2
city=input("enter city:")
url="https://www.weather-forecast.com/locations/" + city +"/forecasts/latest"
data=urllib2.urlopen(url).read()
print(data.decode('utf-8'))

当我输入时它工作正常

进入城市:"纽约">

虽然相同的代码会抛出错误HTTPError: HTTP Error 404: Not Found如果输入是

进入城市:"纽蛋黄">

您可以使用 try-except 语句来解决此问题

city=input("enter city:")
url="https://www.weather-forecast.com/locations/" + city +"/forecasts/latest"
try:
data=urllib2.urlopen(url).read()
print(data.decode('utf-8'))
except:
print('The entered city does not exist.Please enter a valid city name')

尝试使用requests库它起作用了。

import requests
city = input("entercuty:")
url = "https://www.weather-forecast.com/locations/"+city+"/forecasts/latest"
data = requests.get(url)
print(data.status_code)
print(data.text)

将城市命名为"斯图加特"。

状态代码:200

最新更新