python 的请求模块中的代理中的 '\n'

'\n' in proxies in requests module of python

我在请求中使用代理 python 并且遇到了这个问题。

proxy = '159.197.128.8:3128'
response = s.get('http://ipv4.icanhazip.com', 
                 timeout=10,
                 proxies={"http": f"http://{proxy}", "https": f"http://{proxy}"},
                 headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.94 Chrome/37.0.2062.94 Safari/537.36'})
print(response.content)

这段代码工作得很好..当我在代理的末尾添加一个'\n'时..即

proxy=proxy+'\n'

它仍然有效,但添加两个 '\n' returns 错误“解析失败” 我不知道 requests 如何解析代理以及为什么末尾的 '\n' 没有影响..请帮助我理解这个

只要跟随回溯,看看解析代理的内容是什么-url。

requests用于HTTPAdapter.get_connection() urllib3's parse_url方法。
但是,正则表达式用于匹配 url(与 re.match())。正则表达式以 $.

结尾

来自related python docs

$
Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches ‘foo2’ normally, but ‘foo1’ in MULTILINE mode; searching for a single $ in 'foo\n' will find two (empty) matches: one just before the newline, and one at the end of the string.

所以正则表达式匹配字符串直到末尾或直到换行符。因此,re 或多或少会忽略最后一行。
但是如果你现在在你的代理中有两个换行符url,你有一个多行字符串,即使它忽略了最后一个换行符,仍然有一个与正则表达式不匹配的换行符。


这是一个具有相同行为的最小示例:

>>> import re
>>> regex = re.compile(r'^\d$')  # matches exactly one digit
>>> print(re.match(regex, '1'))
<re.Match object; span=(0, 1), match='1'>
>>> print(re.match(regex, '1\n'))
<re.Match object; span=(0, 1), match='1'>
>>> print(re.match(regex, '1\n\n'))
None