【问题标题】:How can I implement my PHP curl request to Python如何实现我的 PHP curl 请求到 Python
【发布时间】:2010-09-29 01:20:45
【问题描述】:

下面的 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 实现,但我还不知道该怎么做。

【问题讨论】:

    标签: php python curl urllib2 pycurl


    【解决方案1】:

    有用于 Python 的 cURL 包装器,但首选方法是使用 urllib2

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

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

    【讨论】:

    • 是的,但是我让 form.php 只输出表单标签,而没有其他常见内容,如页眉、页脚……只是表单。
    • 如果你控制了两个服务器,为什么还要使用 cURL?
    • 我只能控制 Server-A.com。 Server-B.com 托管在其他地方,并建立在 Django 之上。我只能向另一端的人请求(并建议)他如何以代理方式从 Server-A.com 获取数据。
    • @r2b2 你应该向他要一个 API。这对你们俩都会更容易。但如果他不合作,urllib 将和 cURL 一样工作
    • 我尝试在 linux 命令行上运行你的代码,它给了我这个:NameError: name 'urllib2' is not defined
    【解决方案2】:

    我很确定这就是您要查找的内容:http://pycurl.sourceforge.net/ 祝你好运!

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2013-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 2021-09-30
        相关资源
        最近更新 更多