Redirect Python在向URL中输入表情符号时请求模块崩溃。为什么?

Redirect Python在向URL中输入表情符号时请求模块崩溃。为什么?,redirect,python-requests,Redirect,Python Requests,我正在尝试清理以下站点: 我得到: raise TooManyRedirects('Exceeded {} redirects.'.format(self.max_redirects), response=resp) requests.exceptions.TooManyRedirects: Exceeded 30 redirects. 我想知道发生了什么事。我怀疑某些循环是由被解释的特殊字符产生的,但我不知所措。你问为什么会发生这种情况。这是由于使用urllib3的请求造成的。在规

我正在尝试清理以下站点:

我得到:

    raise TooManyRedirects('Exceeded {} redirects.'.format(self.max_redirects), response=resp)
requests.exceptions.TooManyRedirects: Exceeded 30 redirects.

我想知道发生了什么事。我怀疑某些循环是由被解释的特殊字符产生的,但我不知所措。

你问为什么会发生这种情况。这是由于使用urllib3的请求造成的。在规范化过程中,urllib3根据RFC 3986的建议将编码字节百分比更改为大写。在正常情况下,这将是好的。但是这个服务器似乎希望它的URL是小写的。这可以通过以下方式看到:

import requests
url = 'https://nypost.com/2020/06/27/milton-glaser-designer-of-i-%e2%99%a5%e2%80%8a-ny-logo-dead-at-91/'
resp = requests.get(url, allow_redirects=False)

print(resp.status_code)
print(resp.headers['Location'])
print(resp.url)
产出:

301 
https://nypost.com/2020/06/27/milton-glaser-designer-of-i-%e2%99%a5%e2%80%8a-ny-logo-dead-at-91/
https://nypost.com/2020/06/27/milton-glaser-designer-of-i-%E2%99%A5%E2%80%8A-ny-logo-dead-at-91/
这表明它是一个HTTP 301重定向。它重定向到的URL和请求的URL

您可以通过打开Firefox或Chrome,右键单击页面,选择Inspect,然后选择Network,选择disable cache,然后粘贴最后一个URL并点击return来测试这一点。您将看到301重定向

我希望服务器上有一个指令,通过强制重定向使所有URL都小写。因此,它进入一个循环,使用大写百分比编码字节进行请求,并被重定向到一个使用小写百分比编码字节的URL,它使用大写百分比编码字节向该URL发出请求,等等

有一种方法可以解决这个问题,但它可能会导致意想不到的副作用,我只会把它作为最后的手段,然后只有当你确定你的所有URL的格式都是服务器所期望的。但这解释了问题所在

import requests.packages.urllib3.util.url as _url
import requests


def my_encode_invalid_chars(component, allowed_chars):
    return component


_url._encode_invalid_chars = my_encode_invalid_chars
url = 'https://nypost.com/2020/06/27/milton-glaser-designer-of-i-%e2%99%a5%e2%80%8a-ny-logo-dead-at-91/'
resp = requests.get(url)

print(resp.status_code)
print(resp.headers)
print(resp.url)
print(resp.text)
注:输出为:

200
{'Server': 'nginx', ... 
https://nypost.com/2020/06/27/milton-glaser-designer-of-i-%e2%99%a5%e2%80%8a-ny-logo-dead-at-91/
响应是HTTP200OK。 没有位置标头(我截断了输出)。 请求的URL是小写的。
然后打印页面源代码。

使用
site=>https://nypost.com/2020/06/27/milton-glaser-designer-of-i-♥-ny-logo-dead-at-91/'
这不起作用。我从beautifulsoup findall获得%编码。是的。。我不是手动喂食,非常感谢!这帮了大忙。我需要记住这一点,以避免脚本崩溃或无法正常工作。再次感谢
200
{'Server': 'nginx', ... 
https://nypost.com/2020/06/27/milton-glaser-designer-of-i-%e2%99%a5%e2%80%8a-ny-logo-dead-at-91/