在python的世界里,有很多库被设计用来发起http访问。

以下列举常用的方法:

  • urllib,有urlencode方法,在urllib2中没有
  • urllib2,可以接受Request对象,可以伪装agent,但是urllib不行
  • urllib3,还没研究过
  • httplib, 据说是urllib是在这个上面封装的
  • httplib2
  • requests

据说以上最好用的还是Requests,Requests使用文档 传送门

talk is cheap,show me the code!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import requests
resp = requests.get('http://www.badu.com')
# 如果是api请求,返回是json,则可以直接获取
dict = resp.json()
# 如果是普通的http请求,则可以通过以下方式获取返回数据
text = resp.text

# 以下的方法可以保存cookie
s = requests.Session()
s.get('http://httpbin.org/get')

# get 请求
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)
# http://httpbin.org/get?key1=value1&key2=value2&key2=value3

# post 请求
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)

# post with json请求, 适用于微信公众号的某些接口
madminyload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", json=payload)
print(r.text)