Home > Article > Backend Development > Why Am I Getting a \"403 Forbidden\" Error When Using Python Requests to Access a Website?
When attempting to parse a website using Python requests, you may encounter a "403 Forbidden" error. This error signifies that the website has rejected your GET request.
Upon analyzing the problem, it was discovered that the website was rejecting GET requests without a specified User-Agent. To resolve this issue, the following code snippet can be used to set the User-Agent header:
<code class="python">import requests url = 'http://worldagnetwork.com/' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} result = requests.get(url, headers=headers) print(result.content.decode())</code>
By setting the User-Agent header to match that of a popular browser, the code mimics a genuine user visit and allows the parsing to succeed.
The above is the detailed content of Why Am I Getting a \"403 Forbidden\" Error When Using Python Requests to Access a Website?. For more information, please follow other related articles on the PHP Chinese website!