Reputation:
Does anybody know why is it doing this error? I can't seem to request the web page
urllib.error.HTTPError: HTTP Error 403: Forbidden
This is my code
from urllib.request import urlopen
txt_file = urlopen("https://www.py4e.com/code3/mbox.txt")
Upvotes: 0
Views: 29
Reputation: 6625
This server seems to be configured to reject requests without a user agent. Send a user agent and it works correctly:
import requests
url = 'https://www.py4e.com/code3/mbox.txt'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
response = requests.get(url, headers=headers)
print(response.content)
Upvotes: 2