如何将我的PHP curl请求转换为Python

0 投票
3 回答
2120 浏览
提问于 2025-04-16 04:43

下面这段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

你可以使用Requests库来进行网络请求。

下面是一个示例的GET请求:

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

0

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

1

Python有一些可以用来处理cURL的工具,但更推荐的方式是使用urllib2这个库。

需要注意的是,你在PHP中的代码是获取整个网页并打印出来。在Python中,等效的代码是:

import urllib2

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

撰写回答