【问题标题】:What is the suggested way to build and send a http request in Python在 Python 中构建和发送 http 请求的建议方法是什么
【发布时间】:2014-11-19 20:25:27
【问题描述】:

我写了一个大约 1 岁的小模块。
这几天尝试添加一些功能的时候,发现python的urllib有了很大的变化,我对如何构建请求感到困惑。

在旧模块中,FancyURLopener 被用作我的基类,但我发现它自 3.3 版起已弃用。

所以我再次阅读了文档,并尝试构建一个请求而不是打开器。

但是,当我尝试添加标题时,只提供了一个函数Request.add_header(key, val)。我有像这样从提琴手复制的标题:

GET some_url HTTP/1.1
Host: sosu.qidian.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: zh-cn,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Referer: anothe_url
Cookie: a lot of data
Connection: keep-alive

所以我必须将它们一一添加到请求中吗?

我还发现了另一个打开器urllib.request.build_opener(),它可以一次添加很多标题。但我无法设置方法 'get' 或 'post'。

我是python新手,有什么建议吗?

【问题讨论】:

    标签: python xmlhttprequest


    【解决方案1】:

    到目前为止,在 Python 中发出 http 请求的最佳方式是安装和使用此模块:
    http://docs.python-requests.org/en/latest/

    你可以这样写代码:

    headers = {
        'X-Requested-With': 'XMLHttpRequest',
        'Referer': 'anothe_url',
        # etc
    }
    response = requests.get(some_url, headers=headers)
    

    http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 2014-08-22
      相关资源
      最近更新 更多