如何在 Python 中发送 HTTP Get Web 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17178483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:41:11  来源:igfitidea点击:

How do you send an HTTP Get Web Request in Python?

pythonhttpstreamreaderwebrequest

提问by LeChosenOne

I am having trouble sending data to a website and getting a response in Python. I have seen similar questions, but none of them seem to accomplish what I am aiming for.

我无法将数据发送到网站并在 Python 中获得响应。我见过类似的问题,但似乎没有一个能实现我的目标。

This is my C# code I'm trying to port to Python:

这是我尝试移植到 Python 的 C# 代码:

    static void Request(Uri selectedUri)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(selectedUri);
        request.ServicePoint.BindIPEndPointDelegate = BindIPEndPointCallback;
        request.Method = "GET";
        request.Timeout = (int)Timeout.TotalMilliseconds;
        request.ReadWriteTimeout = (int)Timeout.TotalMilliseconds;
        request.CachePolicy = CachePolicy;
        request.UserAgent = UserAgent;

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
            {
                string responseText = responseReader.ReadToEnd();
                File.WriteAllText(UrlFileName, responseText.Trim(), Encoding.ASCII);
            }
        }
     }

Here is my attempt in Python:

这是我在 Python 中的尝试:

def request():
web = httplib.HTTPConnection('https://someurl.com');
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
web.request("GET", "/heartbeat.jsp", headers);
response = web.getresponse();
stream = ""; #something is wrong here

Any help would be appreciated!

任何帮助,将不胜感激!

采纳答案by Victor Castillo Torres

You can use urllib2

您可以使用urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

你也可以使用httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

请求库

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

回答by Sam

In Python, you can use urllib2(http://docs.python.org/2/library/urllib2.html) to do all of that work for you.

在 Python 中,您可以使用urllib2( http://docs.python.org/2/library/urllib2.html) 为您完成所有这些工作。

Simply enough:

很简单:

import urllib2
f =  urllib2.urlopen(url)
print f.read() 

Will print the received HTTP response.

将打印收到的 HTTP 响应。

To pass GET/POST parameters the urllib.urlencode()function can be used. For more information, you can refer to the Official Urllib2 Tutorial

要传递 GET/POST 参数,urllib.urlencode()可以使用该函数。更多信息可以参考Urllib2官方教程