urllib 重定向错误

urllib redirect error

我正在尝试使用 urllib 和 BeautifulSoup 抓取表格,但出现错误:

"urllib.error.HTTPError: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: Found"

我听说这与需要 cookie 的网站有关,但在我第二次尝试后仍然出现此错误:

import urllib.request
from bs4 import BeautifulSoup
import re

opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
file = opener.open(testURL).read().decode()
soup = BeautifulSoup(file)
tables = soup.find_all('tr',{'style': re.compile("color:#4A3C8C")})
print(tables)

几点建议:

  • 如果您必须处理 cookie,请使用 HTTPCookieProcessor
  • 您不必使用自定义用户代理,但如果您想模拟 Mozilla,则必须使用它的全名。此站点不接受 'Mozilla/5.0' 并将继续重定向。
  • 您可以使用 HTTPError 捕获此类异常。

opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor())
user_agent = 'Mozilla/5.0 (Windows NT 6.1; rv:54.0) Gecko/20100101 Firefox/54.0'
opener.addheaders = [('user-agent', user_agent)]

try:
    response = opener.open(testURL)
except urllib.error.HTTPError as e:
    print(e)
except Exception as e:
    print(e)
else: 
    file = response.read().decode()
    soup = BeautifulSoup(file, 'html.parser')
    ... etc ...