【问题标题】:python requests return a different web page from browser or urllibpython请求从浏览器或urllib返回不同的网页
【发布时间】:2017-04-08 23:39:28
【问题描述】:

我使用请求来抓取网页中的某些内容。
当我使用

import requests  
requests.get('example.org')

我得到的页面与我使用浏览器或使用时得到的页面不同

import urllib.request
urllib.request.urlopen('example.org')

我尝试使用urllib,但速度真的很慢。
在一个比较测试中,我做的比requests慢了50%!!

你是怎么解决这个问题的?

【问题讨论】:

    标签: python python-requests urllib


    【解决方案1】:

    经过大量调查,我发现该站点仅在附加到该站点的第一个访问者的标题中传递了一个 cookie。

    所以解决方案是使用 head 请求获取 cookie,然后使用您的 get 请求重新发送它们

    import requests  
    # get the cookies with head(), this doesn't get the body so it's FAST
    cookies = requests.head('example.com')
    # send get request with the cookies
    result = requests.get('example.com', cookies=cookies)
    

    现在它比 urllib + 相同的结果更快:)

    【讨论】:

    • 或者您可以使用Session 实例。它将自动管理带有CookieJar的cookie。
    • 我试过了,但在我的情况下,cookie 仅与第一个请求一起发送,我不想在后续请求中重用相同的 cookie,所以我只是将 cookie 传递给 get 请求。对于大多数其他情况,您的建议仍然有效
    猜你喜欢
    • 2023-02-17
    • 2020-12-31
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    相关资源
    最近更新 更多