urllib.error.URLError
是Python中urllib
库抛出的异常,表示在尝试访问URL时发生了错误。403错误是HTTP状态码,表示"禁止访问"(Forbidden),服务器理解请求但拒绝授权。
出现urllib.error.URLError: urllib.request.urlopen错误403:禁止使用HTTP
可能有以下几种原因:
import urllib.request
url = "http://example.com"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
req = urllib.request.Request(url, headers=headers)
try:
response = urllib.request.urlopen(req)
print(response.read().decode('utf-8'))
except urllib.error.URLError as e:
print(f"Error: {e.reason}")
许多网站已禁用HTTP协议,尝试将URL中的http://
改为https://
import urllib.request
class RedirectHandler(urllib.request.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
return urllib.request.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
opener = urllib.request.build_opener(RedirectHandler)
urllib.request.install_opener(opener)
try:
response = urllib.request.urlopen("http://example.com")
print(response.read().decode('utf-8'))
except urllib.error.URLError as e:
print(f"Error: {e.reason}")
考虑使用requests
库,它提供了更简单的API和更好的错误处理:
import requests
url = "http://example.com"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # 如果请求不成功会抛出异常
print(response.text)
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
这种错误常见于: