Warm tip: This article is reproduced from serverfault.com, please click

Sending header requests via dictionary in python

发布于 2020-12-05 00:23:51

I am making a very obvious mistake which I am not able to figure out. Below is the code snippet:

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!')

The script takes various User agent and tries to send GET requests via various Chrome browser version. I am getting the following error as a result of it

Other error occurred: {'str' object has no attribute 'items'}

I tried converting to dict using the below method to convert to dictionary from string:

header=eval(header)

But seeing the below message then:

'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

Please can someone help me here or else how can I correct my headers data structure. Thanks!

Questioner
deep
Viewed
0
deep 2020-12-05 08:29:02

This did the trick:

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