pythonpython-requestscross-browserrequest-headershttp-request-attribute

Getting requests.exceptions.InvalidHeader: Header part (1) from ('Sec-Gpc', 1) must be of type str or bytes, not <class 'int'> though Chrome sends it


I get requests.exceptions.InvalidHeader: Header part (1) from ('Sec-Gpc', 1) must be of type str or bytes, not <class 'int'> when trying to use the Sec-Gpc attribute in a header:

headers = {
    ...,
    "Sec-Gpc": 1,
    ...
}

I tried checking MDN, but the browser compatibility table says Chrome doesn't support it, but when I check the request headers, Chrome sends it.

In this issue, an extension is said to modify the headers and that Chrome doesn't support it, but I don't have that extension in my requests/driver. So, why do I get the error, and how do I pass the attribute, preferably without any third-party libraries?


Solution

  • Don't put integer as value in headers, convert it to string. E.g.:

    import requests
    
    url = "https://httpbin.org/headers"
    
    headers = {"Sec-Gpc": "1"}
    
    print(requests.get(url, headers=headers).text)
    

    Prints:

    {
      "headers": {
        "Accept": "*/*", 
        "Accept-Encoding": "gzip, deflate, br", 
        "Host": "httpbin.org", 
        "Sec-Gpc": "1", 
        "User-Agent": "python-requests/2.31.0", 
      }
    }