urllib.error.HTTPError:HTTP错误302

时间:2018-04-05 17:21:38

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

我正在尝试使用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')

}

有人可以告诉我为什么会抛出这个错误,意味着什么以及如何解决这个错误?

2 个答案:

答案 0 :(得分:0)

如评论中所述:

  

该网站设置了一个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'}

答案 1 :(得分:0)

找到的超文本传输​​协议(HTTP)302重定向状态响应代码表示所请求的资源已被临时移动到位置标头提供的URL。浏览器重定向到此页面,但是搜索引擎不会更新其到资源的链接(在“ SEO说”中,据说“链接汁”未发送到新URL)。

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

在希望将方法更改为GET的情况下,请改用303请参阅其他。当您想响应一个PUT方法而不是上载的资源,而是一个确认消息,例如:“您已成功上载XYZ”时,这很有用。