Python 中的 cURL 帮助
我必须向服务器发送请求。在该网站的 API 文档中,有一个在 PHP 中使用 cURL 的示例:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.website.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "request=$wrapper");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
;
$data = curl_exec($ch);
curl_close($ch);
但是我的应用程序是使用 Python 完成的,所以我尝试编写类似的内容,但此代码不起作用:
req = urllib2.Request(url, formatted)
response = urllib2.urlopen(req)
html = response.read()
print html+"\n\n"
你能帮我编写一个工作转换吗PHP cURL 程序到 Python?
谢谢你!!
I have to POST a request to a server. In the API documentation of the website there is this example that uses cURL in PHP:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.website.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "request=$wrapper");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
;
$data = curl_exec($ch);
curl_close($ch);
But my app is done using Python, so I tried to write something like that but this code doesn't work:
req = urllib2.Request(url, formatted)
response = urllib2.urlopen(req)
html = response.read()
print html+"\n\n"
Can you help me write a working conversion of a PHP cURL program to Python?
Thank you!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
curl 也适用于 Python: http://pycurl.sourceforge.net/
该示例可以翻译为 Python和 pycurl 像这样:
您使用 urllib2 的 Python 代码看起来不错,它应该可以工作。可能您没有提到的其他内容有错误;您能说得更具体一些吗?
curl is for Python too: http://pycurl.sourceforge.net/
The example could be translated into Python and pycurl like this:
Your Python code using urllib2 looks OK, it should be working. Probably there is an error in something other you did not mention in question; could you be please more specific?
考虑使用数据包嗅探器来确定 cURL 是否正在发送用户代理信息。如果是,并且服务需要该信息,则在 请求(来自 urllib2 文档,页面底部):
Consider using a packet sniffer to figure out if cURL is sending User-Agent information. If it is, and the service is expecting that information, then use the add_header() method on your Request (from urllib2 documentation, bottom of page):
考虑你的代码,这实际上应该有效。
您遇到的错误是什么?
Taking your code, this should actually work.
What is the error you are getting?
这很尴尬,但是...我使用 urllib 和 urllib2 的代码的唯一问题是...该代码执行 GET 而不是 POST !
这里是我使用 Wireshark 进行的扫描:
1- 使用 urllib 和 urllib2
2- 使用 PyCurl
所以代码可以工作,但它不适合我,因为我需要 POST,但我更喜欢使用 NOT PyCurl。
有什么想法吗?
非常感谢!!
It's quite embarrassing but... the only problem with my code that uses urllib and urllib2 is... that this code do a GET and not a POST !!!
Here my scan using Wireshark:
1- using urllib and urllib2
2- using PyCurl
so the code works, but it's not right for me because i need a POST, but i will prefer to use NOT PyCurl.
Any idea?
Thank you very much!!