Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何处理<;TooManyRedirects:超过30个重定向。>;在Python中使用请求时出现异常?_Python_Url_Python Requests - Fatal编程技术网

如何处理<;TooManyRedirects:超过30个重定向。>;在Python中使用请求时出现异常?

如何处理<;TooManyRedirects:超过30个重定向。>;在Python中使用请求时出现异常?,python,url,python-requests,Python,Url,Python Requests,我使用的请求效果很好,但是使用这个特定的url,我得到了重定向循环中断 s = requests.Session() page = s.get('http://pe.usps.gov/text/pub28/28apc_002.htm') tree = html.fromstring(page.content) street_type = tree.xpath(r"//*[@id='ep533076']/tbody/tr[2]/td[1]/p/a") print(street_type) 我特别

我使用的请求效果很好,但是使用这个特定的url,我得到了重定向循环中断

s = requests.Session()
page = s.get('http://pe.usps.gov/text/pub28/28apc_002.htm')
tree = html.fromstring(page.content)
street_type = tree.xpath(r"//*[@id='ep533076']/tbody/tr[2]/td[1]/p/a")
print(street_type)
我特别想知道是否有一种方法可以为请求分配头以避免重定向。我已经测试了实际的url,它看起来是有效的


谢谢

重定向是服务器发送的响应。它通常是一个HTTP
响应,上面写着“嘿,我知道你在找什么,它在这里…”并向你发送一个新的查找位置。是的,这些可以链接在一起,是的,你可以在循环中结束。这就是最大重定向限制的目的

您可以使用以下命令设置请求中允许的重定向数:

s.max_redirects = 50   # the default is 30
但这并不能解决问题。在这种情况下,服务器会查找您正在使用的浏览器类型,并在找不到所需内容时重定向您。通过在标题中添加
用户代理
字段,可以模拟浏览器

推荐用法:为单个请求将标题设置为通用浏览器

session.get(url, headers={'user-agent': 'My app'})

# returns:
<Response [200]>
session.get(url,头={'user-agent':'My-app'})
#返回:
原始发布:设置整个会话的标题,这不一定是您想要的

s.headers = {'user-agent': 'some app'}
s.get('http://pe.usps.gov/text/pub28/28apc_002.htm')

# returns:
<Response [200]>
s.headers={'user-agent':'someapp'}
s、 得到('http://pe.usps.gov/text/pub28/28apc_002.htm')
#返回:

在这种情况下,您不需要欺骗浏览器用户代理,我建议您仅在必要时使用欺骗。而是包括一个特定于应用程序的用户代理;e、 g.
session.header['User-Agent']=“我的应用程序”
这可能是真的。我刚刚从firebug中复制了它。另外,为了完整起见,您可能应该添加一条信息,您可以使用headers kwarg向单个请求添加头,而不是向整个会话添加头
session.get(url,headers={'user-agent':'myapp'})
还有它的
headers
not
header