刘看山城市冰屋
刘看山城市冰屋
3月前 · 3 人阅读

python3.x里面urllib不流行了,开始用requests包。

1、安装requests包
1)pip安装

pip install requests

2)pycharm里面安装:
先打开设置,点加号,

然后搜索requests,点install

2、get请求

import requests
r = requests.get("http://xxxxx?name=aaa")
print(r.text)

3、post请求

import requests
postdata = { 'name':'aaa' }
r = requests.post("http://xxxxx?name=aaa",data=postdata)
print(r.text)

4、其他类型的请求

>>> r = requests.put("http://httpbin.org/put")
>>> r = requests.delete("http://httpbin.org/delete")
>>> r = requests.head("http://httpbin.org/get")
>>> r = requests.options("http://httpbin.org/get")

5、json方式传参——不用再拼url了

#example1:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)

#example2:
>>> 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

4、带session请求

s = requests.Session()
headers = { 'Host':'www.xxx.com'}
postdata = { 'name':'aaa' }
url = "http://xxxxx"
s.headers.update(headers)
r = s.post(url,data=postdata)
print(r.text)

比urllib和urllib2简单好多有木有。

更详细的资料参考,介绍的超好:
http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

收藏 0
关键词: requests http get org httpbin
评论