如何将我的PHP curl请求实现到Python

时间:2010-09-29 01:20:46

标签: php python curl urllib2 pycurl

下面的PHP代码从服务器A获取html到服务器B.我这样做是为了规避浏览器的同域策略。 (jQuery的JSONP也可用于实现此目的,但我更喜欢这种方法)

<?php
 /* 
   This code goes inside the body tag of server-B.com.
   Server-A.com then returns a set of form tags to be echoed in the body tag of Server-B 
 */
 $ch = curl_init();
 $url = "http://server-A.com/form.php";
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_HEADER,FALSE);
 curl_exec($ch);     //   grab URL and pass it to the browser
 curl_close($ch);    //   close cURL resource, and free up system resources
?>

我如何在Python中实现这一目标?我确定在Python中也有Curl实现,但我还不知道该怎么做。

3 个答案:

答案 0 :(得分:1)

Python有cURL包装器,但执行此操作的首选方法是使用urllib2

请注意,PHP中的代码会检索整个页面并将其打印出来。等效的Python代码是:

import urllib2

url = 'http://server-A.com/form.php'
res = urllib2.urlopen(url)
print res.read()

答案 1 :(得分:0)

我很确定这就是你要找的东西:http://pycurl.sourceforge.net/ 祝你好运!

答案 2 :(得分:0)

您可以使用Requests library

示例获取电话

import requests

def consumeGETRequestSync():
 params = {'test1':'param1','test2':'param2'}
 url = 'http://httpbin.org/get'
 headers = {"Accept": "application/json"}
 # call get service with headers and params
 response = requests.get(url, headers = headers,data = params)
 print "code:"+ str(response.status_code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "content:"+ str(response.text)

consumeGETRequestSync()

您可以查看此博文http://stackandqueue.com/?p=75