mercredi 27 octobre 2021

urllib sometimes doesn't open websites

I have a problem I can't really fathom... Sometimes I provide a Python app with a link to a txt web page and the app processes it as expected but sometimes I simply get errors, although the links seem basically identical (meaning they're both simple text-based web pages).

For example, I have a simple code like this:

import urllib.request, urllib.parse, urllib.error


link = input("Link: ")

fhand = urllib.request.urlopen(link)

for line in fhand:
    print(line.decode())

When I type http://data.pr4e.org/romeo-full.txt as a link, it works. But when I type https://www.py4e.com/code3/romeo.txt, it doesn't. How come?

The errors I get:

Traceback (most recent call last):

  File "C:\Users\lukas\AppData\Roaming\JetBrains\PyCharmCE2021.2\scratches\scratch_11.py", line 7, in <module>
    fhand = urllib.request.urlopen(link)
  File "C:\Users\lukas\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\lukas\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
    response = meth(req, response)
  File "C:\Users\lukas\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
    response = self.parent.error(
  File "C:\Users\lukas\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
    return self._call_chain(*args)
  File "C:\Users\lukas\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
  File "C:\Users\lukas\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden



Aucun commentaire:

Enregistrer un commentaire