78

我无法将数据发送到网站并在 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);
            }
        }
     }

这是我在 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

任何帮助,将不胜感激!

4

2 回答 2

160

你可以使用urllib2

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

你也可以使用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

请求库

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200
于 2013-06-18T21:28:02.517 回答
7

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

很简单:

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

将打印收到的 HTTP 响应。

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

于 2013-06-18T20:55:52.223 回答