python - 通过python中的字典发送标头请求
问题描述
我犯了一个非常明显的错误,我无法弄清楚。下面是代码片段:
def test_chrome_header():
headers = {1:"'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97'",
2:"'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'"}
for key, header in headers.items():
try:
response = requests.get("https://www.example.com", proxies=proxies, headers=header, verify=False)
response.raise_for_status()
print(response.status_code)
except HTTPError as http_err:
print('HTTP error occurred: {%s}'%http_err)
except Exception as err:
print('Other error occurred: {%s}'%err)
else:
print('Success for Chrome!')
该脚本采用各种用户代理并尝试通过各种 Chrome 浏览器版本发送 GET 请求。因此,我收到以下错误
Other error occurred: {'str' object has no attribute 'items'}
我尝试使用以下方法转换为 dict 从字符串转换为字典:
header=eval(header)
但是看到以下消息:
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97'
^
SyntaxError: invalid syntax
请有人可以在这里帮助我,否则我该如何更正我的标题数据结构。谢谢!
解决方案
这成功了:
headers = {
1:{'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97'},
2:{'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
}
推荐阅读
- python - 如何在 Python 中矢量化这些嵌套循环?
- asp.net-web-api - 如何在 asp.net 中使 web.config 参数化
- java - 如何定义另一个类在 MainActivity 中调用的方法?
- android - 芯片 setoncheckedchangelistener 字符串比较返回 false
- mysql - 我只想显示 MySQL 数据库中今天和未来 30 天之间的日期
- java - (Antlr)如何在终端中运行此输入并获取输出?
- python - Django 没有为 AnonymousUser- Django rest api 提供数据库表示
- react-native - react-native run-android无法在空对象上获取属性'packageName'
- python - 从 glob.glob("D\\*.txt") 获取 r"D:\test.txt" 或 "D:\\test.txt"
- c - 将 void 转换为具有相同格式的结构