Python 执行 HTTP 命令
简单来说,我发现把某些特定的字符串输入到浏览器的地址栏里,会让我得到一些不错的结果。比如说:http://myip:myport/?CreateOrder=Create+New+Order 这个链接可以在我的数据库里创建一个新订单。
我用Python设置了我想要传入这个字符串的变量,但我不知道该用什么方法才能让Python像浏览器一样执行这个字符串。
抱歉我不太懂这些。希望能得到一些帮助。
2 个回答
1
你应该看看Requests
这个模块。
import requests
r = requests.get('http://httpbin.org/get', params={'foo': 'bar'})
print r.content
(httpbin.org是一个很好的服务,可以用来调试HTTP请求)
结果:
{
"url": "http://httpbin.org/get?foo=bar",
"headers": {
"Content-Length": "",
"Accept-Encoding": "identity, deflate, compress, gzip",
"X-Forwarded-Port": "80",
"Host": "httpbin.org",
"Accept": "*/*",
"User-Agent": "python-requests/0.8.3",
"Connection": "keep-alive",
"Content-Type": ""
},
"args": {
"foo": "bar"
},
"origin": "46.64.26.143"
}
2
虽然我不太确定我完全理解你问题的背景,但你可以在Python中使用 urllib2 模块来发送网址请求,特别是可以看看 urlopen
这个函数。
下面是一个你可以用来发送你提到的请求的例子:
import urllib2
url_response = urllib2.urlopen('http://myip:myport/?CreateOrder=Create+New+Order')