3
votes

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:)

2
Try print(url) before opening it, it looks like your URL returns a 404: Not foundgogaz
what did you give as the input?Hari Krishnan
my input was the city tel avivEliza Romanski

2 Answers

1
votes

There must be some spelling mistake in the city name you have entered. I tried running the following code

 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'))

It works properly when i input

enter city:'newyork'

While the same code throws HTTPError: HTTP Error 404: Not Found error if the input is

enter city:'newyolk'

You can solve this by using a try-except statement

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
votes

Tried with requests library it worked.

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)

Gave city as "Stuttgart".

Status code: 200