【问题标题】:urllib.error.HTTPError: HTTP Error 302urllib.error.HTTPError:HTTP 错误 302
【发布时间】:2018-04-05 17:21:38
【问题描述】:

我正在尝试使用 HTML 解析器使用 Python3.6 解析网站,但它会引发如下 ab 错误:

urllib.error.HTTPError:HTTP 错误 302:HTTP 服务器返回一个重定向错误,这将导致无限循环。 最后的 30x 错误消息是: 找到 我写的代码如下: {

from urllib.request import urlopen as uo
from bs4 import BeautifulSoup
import ssl

# Ignore SSL Certification
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter--')
html = uo(url,context = ctx).read()

soup = BeautifulSoup(html,"html.parser")

print(soup)
#retrieve all the anchor tags
#tags = soup('a')

}

谁能告诉我为什么会抛出这个错误,这是什么意思以及如何解决这个错误?

【问题讨论】:

标签: python-3.x beautifulsoup urllib html-parser


【解决方案1】:

如 cmets 所述:

该站点设置一个 cookie,然后重定向到 /Home.aspx。

为避免此站点上的重定向循环,您必须设置 24 个字符 ASP.NET_SessionId cookie。

import urllib.request
opener = urllib.request.build_opener()
opener.addheaders.append(('Cookie', 'ASP.NET_SessionId=garbagegarbagegarbagelol'))
f = opener.open("http://apnakhata.raj.nic.in/")
html = f.read()

但是,我只使用requests

import requests

r = requests.get('http://apnakhata.raj.nic.in/')
html = r.text

默认情况下,它将 cookie 保存到 RequestsCookieJar。在初始请求之后,只会发生一次重定向。你可以在这里看到它:

>>> r.history[0]
[<Response [302]>]

>>> r.history[0].cookies
<RequestsCookieJar[Cookie(version=0, name='ASP.NET_SessionId', value='ph0chopmjlpi1dg0f3xtbacu', port=None, port_specified=False, domain='apnakhata.raj.nic.in', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)]>

要抓取页面,可以使用同一作者创建的requests_html

from requests_html import HTMLSession
session = HTMLSession()
r = session.get('http://apnakhata.raj.nic.in/')

获取链接非常简单:

>>> r.html.absolute_links
{'http://apnakhata.raj.nic.in/',
'http://apnakhata.raj.nic.in/Cyberlist.aspx',
...
'http://apnakhata.raj.nic.in/rev_phone.aspx'}

【讨论】:

    【解决方案2】:

    超文本传输​​协议 (HTTP) 302 Found 重定向状态响应代码表示请求的资源已临时移动到 Location 标头给出的 URL。浏览器会重定向到该页面,但搜索引擎不会更新其指向该资源的链接(在“SEO-speak”中,据说“链接汁”不会发送到新 URL)。

    即使规范要求在执行重定向时不更改方法(和主体),但并非所有用户代理都符合此处 - 您仍然可以在那里找到这种类型的错误软件。因此建议仅将 302 代码设置为 GET 或 HEAD 方法的响应并使用307 Temporary Redirect instead,因为在这种情况下明确禁止更改方法。

    如果您希望将使用的方法更改为 GET,请改用 303 See Other。当您想要对不是上传资源而是确认消息的 PUT 方法做出响应时,这很有用,例如:“您已成功上传 XYZ”。

    【讨论】:

      猜你喜欢
      • 2019-11-05
      • 1970-01-01
      • 2017-05-22
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多