简体   繁体   English

python-requests - 用户代理被覆盖

[英]python-requests - user-agent is being overriden

I have我有

    logindata = {
        'username': 'me',
        'password': 'blbla'
    }
    payload = {'from':'me', 'lang':'en', 'url':csv_url}
    headers = {
        'User-Agent': 'Mozilla/5.0'
    }
    api_url = 'http://dev.mypage.com/admin/app/import/'

    with requests.Session() as s:
        s.post(api_url, data=json.dumps(logindata), headers=headers)

        print s.headers

        # An authorised request.
        r = s.get(api_url, params=payload, headers=headers)

I am getting rejected but it is because of 403 forbidden.我被拒绝了,但这是因为 403 被禁止。 And I printed the headers, I get:我打印了标题,我得到:

..'User-Agent': 'python-requests/2.2.1 CPython/2.7.5 Windows/7'..

Why is my 'User-Agent': 'Mozilla/5.0' getting overriden?为什么我的'User-Agent': 'Mozilla/5.0'被覆盖? what am I missing here?我在这里错过了什么?

headers are not kept inside session this way. headers不会以这种方式保存在会话中

You need to either explicitly pass them every time you make a request, or set the s.headers once:您需要在每次发出请求时明确传递它们,或者设置s.headers一次:

with requests.Session() as s:
    s.headers = {'User-Agent': 'Mozilla/5.0'}

You can check that the correct headers were sent via inspecting response.request.headers :您可以通过检查response.request.headers来检查是否发送了正确的标头:

with requests.Session() as s:
    s.headers = {'User-Agent': 'Mozilla/5.0'}

    r = s.post(api_url, data=json.dumps(logindata))
    print(r.request.headers)

Also see how the Session class is implemented - every time you make a request it merges the request.headers with headers you have set on the session object:另请参阅Session是如何实现的 - 每次发出请求时, 它都会将request.headers您在会话对象上设置的headers合并

headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),

If you want the session to use specific headers for all requests you need to set those headers on the session, explicitly:如果您希望会话对所有请求使用特定标头,则需要在会话上明确设置这些标头:

with requests.Session() as s:
    s.headers.update(headers)
    s.post(api_url, data=json.dumps(logindata))

    # An authorised request.
    r = s.get(api_url, params=payload)

The s.headers.update(headers) line adds your dictionary to the session headers. s.headers.update(headers)行将您的字典添加到会话标题中。

Sessions never copy information from requests to reuse for other requests.会话永远不会从请求中复制信息以重用于其他请求。 Only information from responses (specifically, the cookies) is captured for reuse.仅捕获来自响应(特别是 cookie)的信息以供重用。

For more details, see the requests Session Objects documentation :有关更多详细信息,请参阅requests会话对象文档

Sessions can also be used to provide default data to the request methods.会话还可用于向请求方法提供默认数据。 This is done by providing data to the properties on a Session object.这是通过向 Session 对象上的属性提供数据来完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM