Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the re and urllib.request module

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

like image 462
Eliza Romanski Avatar asked Dec 30 '25 23:12

Eliza Romanski


2 Answers

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')
like image 173
Hari Krishnan Avatar answered Jan 01 '26 12:01

Hari Krishnan


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

like image 30
Praveenkumar Beedanal Avatar answered Jan 01 '26 13:01

Praveenkumar Beedanal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!