urllib雷迪

2024-03-28 11:16:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用urllib和BeautifulSoup来抓取表,但得到了错误:

““urllib.error.HTTPError:HTTP错误302:HTTP服务器返回了将导致无限循环的重定向错误。上一个30x错误消息是: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)

Tags: importrehttptablesrequest错误erroropener
1条回答
网友
1楼 · 发布于 2024-03-28 11:16:42

五点建议:

  • 如果必须处理cookies,请使用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 ...

相关问题 更多 >