大数据 爬虫Python AI Sql

python3.x requests的使用

2018-03-12  本文已影响16人  老胡聊聊天

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

1、安装requests包
1)pip安装

pip install requests

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


image.png

然后搜索requests,点install


image.png

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

上一篇下一篇

猜你喜欢

热点阅读