使用 requests 模拟登录的过程中,从网页上复制的 cookie 中含有特殊字符
cookie = 'xxxxxxxxxxx' # 其中出现了特殊字符
headers = {
'cookie': cookie,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36',
'host': 'www.zhihu.com'
}
res = requests.get('https://www.zhihu.com', headers=headers)
print(res.text)
1. 问题原因
python 文件中设置的编码格式是 utf-8,而复制的 cookie 带有需要进行转义的字符,因此 python 在编译时,将字符串中的字符进行了转义,导致编译后,出现了 ’unicodeescape‘
2. 解决方法限制 python 对字符串进行转义即可,在字符串前添加 r 关键字即可
cookie = r'xxxxxxxxxxx' # 其中出现了特殊字符,添加 r
headers = {
'cookie': cookie,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36',
'host': 'www.zhihu.com'
}
res = requests.get('https://www.zhihu.com', headers=headers)
print(res.text)
3. 方法本质
python字符串前面加上’r’的作用,除了添加 r外,还可以对 python 进行了转义处的字符添加
4. 扩展阅读python3中的unicode_escape



