安装不再赘述,首先导入模块
import requests
#get请求
1,参数传递
>>> import requests
>>> r = requests.get('https://www.douban.com/search', params={'q': 'python', 'cat': '1001'})#发送get请求,get请求如果有参数使用params,会把参数拼到url后面
2,获取结果
>>> r.text
r.text
'<!DOCTYPE HTML>\n<html>\n<head>\n<meta name="description" content="提供图书、电影、音乐唱片的推荐、评论和...'
>>> r.status_code
200
>>> r.url
'https://www.douban.com/search?q=python&cat=1001' #实际请求的链接
>>> r.encoding
'utf-8'
>>> r = requests.get('https://www.douban.com/', headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'}) #需要添加header信息时加上header参数
print(r.text) #结果返回的是字符串
print(r.json()) #结果返回的是字典,返回的数据格式是json字符串才能使用该方法转成dict
>>> r = requests.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json')
>>> r.json()
{'query': {'lang': 'en-US', 'count': 1, 'results': {'channel': {'link': 'http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2151330/', 'atmosphere': {'rising': '0', 'visibility': '16.1', 'pressure': '1036.0', 'humidity': '12'}, .......
无论响应是文本还是二进制内容,我们都可以用content属性获得bytes对象:
>>> r.content
b'<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n...'
3,添加cookie信息
cookie信息可以放到header里一起传递,也可以单独传递
requests.get(url,headers={'cookie':'pt2gguin=o0511402865; RK=JQZpwBp1by; ptcz=6c30e26a9ed6be93d3de9e4c4aca3e55650cf99fcffa64729bd1d58a5fb209d9; pgv_pvi=779236352; pgv_pvid=6970909788; qb_qua=; qb_guid=818de686e29d412fa4ee9e99905ea166; Q-H5-GUID=818de686e29d412fa4ee9e99905ea166; NetType=; pgv_si=s4499960832; FTN5K=0138ca95; pgv_info=ssid=s4269564370; luin=o0511402865; uin=o0511402865; lskey=00010000efc2701412d3429029ac9366e4ba98f0e978e0ae4a9c684101a7b22df0695f534bc242c8d4ff386d; skey=@0sHtvhTsD; ptisp=cnc; p_uin=o0511402865; pt4_token=wGU2YAaM0uu7LbcNjuDcLN-TPrEy7AZw4gcL5TEcKxw_; p_skey=1zg7yvF5wr6l43mfr-BvNHxuVDtybKpR5RbCrgC8weQ_'})
requests.get(url,cookies={'pt2ggui':'o0511402865','RK':'JQZpwBp1by'})
#post请求,get改成post即可。
1,传递表单形式的参数
>>> r = requests.post('https://accounts.douban.com/login', data={'form_email': 'abc@example.com', 'form_password': '123456'})
使用data参数,参数会放到body里传输,使用application/x-www-form-urlencoded
对POST数据编码
2,传递json格式的参数
params = {'key': 'value'}
r = requests.post(url, json=params) # 内部自动序列化为JSON
#上传文件
r = requests.post(url,
data={'session_id':'6ab8785039dcf50fb11c53acc1db7648'},
files={'file_name':open('account.xls','rb') } #加一个文件参数,打开一个文件,filename:指的是你上传之后保存的文件名
)
#下载文件
url = 'https://q4.qlogo.cn/g?b=qq&nk=1834364415&s=140'
r = requests.get(url)
f = open('aa.jpg', 'wb') #创建一个二进制文件
f.write(r.content) #把内容写入二进制文件,完成下载操作
f.close()