im using python 3.7 and i wanted to write a program that takes name of a city and returns the weather forcast . i started my code with :
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)
but when I wanted to read my data i got this error :
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain result = func(*args) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found Process finished with exit code 1
=> can some one help me and tell what is the problem ? thanks:)
答案 0 :(得分: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
错误
输入城市:“ newyolk”
您可以使用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')
答案 1 :(得分:1)
尝试使用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