Python中的简单URL GET/POST函数

81 投票
5 回答
251789 浏览
提问于 2025-04-16 08:42

我在网上找不到相关的信息,但我想要一个这样的功能:

它需要接受三个参数(或者更多,随便):

  • 网址(URL)
  • 一个参数的字典
  • 请求方式(POST 或 GET)

然后返回结果和响应代码。

有没有这样的代码片段可以实现这个功能?

5 个回答

33

你可以用这个来包装urllib2:

def URLRequest(url, params, method="GET"):
    if method == "POST":
        return urllib2.Request(url, data=urllib.urlencode(params))
    else:
        return urllib2.Request(url + "?" + urllib.urlencode(params))

这样做会返回一个 请求 对象,这个对象里面包含了结果数据和响应代码。

53

更简单的方法是通过 requests 模块来实现。

import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)

如果你想发送的数据不是表单编码的,可以把它转换成字符串的形式发送(下面的例子来自于文档):

import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)
111

requests

https://github.com/kennethreitz/requests/

这里有一些常见的用法:

import requests
url = 'https://...'
payload = {'key1': 'value1', 'key2': 'value2'}

# GET
r = requests.get(url)

# GET with params in URL
r = requests.get(url, params=payload)

# POST with form-encoded data
r = requests.post(url, data=payload)

# POST with JSON 
import json
r = requests.post(url, data=json.dumps(payload))

# Response, status etc
r.text
r.status_code

httplib2

https://github.com/jcgregorio/httplib2

>>> from httplib2 import Http
>>> from urllib import urlencode
>>> h = Http()
>>> data = dict(name="Joe", comment="A test comment")
>>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
>>> resp
{'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent',
 'server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT', 
 'content-type': 'text/html'}

撰写回答