Wysyłanie "User-agent" za pomocą biblioteki zapytań w Pythonie

Chcę wysłać wartość dla "User-agent" podczas żądania strony internetowej za pomocą zapytań Pythona. Nie jestem pewien, czy jest to w porządku, aby wysłać to jako część nagłówka, jak w kodzie poniżej:

debug = {'verbose': sys.stderr}
user_agent = {'User-agent': 'Mozilla/5.0'}
response  = requests.get(url, headers = user_agent, config=debug)

Informacje debugowania nie pokazują nagłówków wysyłanych podczas żądania.

Czy jest dopuszczalne wysyłanie tych informacji w nagłówku? Jeśli nie, jak mogę go wysłać?

Author: charleslparker, 2012-05-15

2 answers

user-agent należy określić jako pole w nagłówku.

Oto lista pól nagłówka HTTP i prawdopodobnie zainteresują cię pola specyficzne dla żądań , które zawierają User-Agent.

Jeśli używasz requests v2.13 i nowszych

Najprostszym sposobem na zrobienie tego, co chcesz, jest utworzenie słownika i bezpośrednie określenie nagłówków, w ten sposób:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

Jeśli używasz requests v2. 12.x i starsze

Starsze wersje requests clobbered domyślne nagłówki, więc powinieneś wykonać następujące czynności, aby zachować domyślne nagłówki, a następnie dodać do nich własne.

import requests

url = 'SOME URL'

# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()

# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)
 246
Author: wkl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-05 20:25:42

Wygodniej jest używać sesji , w ten sposób nie musisz pamiętać o ustawianiu nagłówków za każdym razem:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

Domyślnie sesja zarządza również Plikami cookie. Jeśli chcesz to wyłączyć, zobacz to pytanie .

 22
Author: user,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-10 01:38:20