首页 > 解决方案 > 通过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

请有人可以在这里帮助我,否则我该如何更正我的标题数据结构。谢谢!

标签: pythonapipython-requestshttp-headers

解决方案


这成功了:

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'}
        }

推荐阅读