01,requests模块
一、request模块简介
介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) 安装:pip3 install requests #各种请求方式:常用的就是requests.get()和requests.post() >>> import requests >>> r = requests.get('https://api.github.com/events') >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'}) >>> r = requests.put('http://httpbin.org/put', data = {'key':'value'}) >>> r = requests.delete('http://httpbin.org/delete') >>> r = requests.head('http://httpbin.org/get') >>> r = requests.options('http://httpbin.org/get')
一、GET请求
1、基本请求
import requests response=requests.get('http://dig.chouti.com/') print(response.text)
2、get请求传参 params
①直接URL传参 (如果参数是中文或者有其他特殊符号,则不得不进行url编码)
import requests response=requests.get('https://www.baidu.com/s?wd=python&pn=1') print(response.text)
#如果查询关键词是中文或者有其他特殊符号,则不得不进行url编码 from urllib.parse import urlencode wd='美女' encode_res=urlencode({'k':wd},encoding='utf-8') keyword=encode_res.split('=')[1] print(keyword) # 然后拼接成url url='https://www.baidu.com/s?wd=%s&pn=1' %keyword response=requests.get(url)
②使用params 传参 (字符类型)(可直接传中文、特殊字符)
import requests url='https://www.baidu.com/s?wd=%s&pn=1' response=requests.get(url,params='美女')
2、get请求请求头 headers (字典类型)
headers={ 'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36', } respone=requests.get('https://www.zhihu.com/explore', headers=headers)
3、get请求 cookies(字典类型)
import requests Cookies={ 'user_session':'rzNme4L6LTH7QSresq8w0BVYhTNt5GS-asNnkOe7_FZ2CjB6', } response=requests.get('https://github.com/settings/emails', cookies=Cookies)
二、post请求
headers、cookies 同get请求
1、post请求传参 date (字典类型)
requests.post(url='xxxxxxxx', data={'xxx':'yyy'}) #没有指定请求头,#默认的请求头:application/x-www-form-urlencoed
2、post请求传参json (json格式)
requests.post(url='', json={'':1}, ) #默认的请求头:application/json
注意点
#如果我们自定义请求头是application/json,并且用data传值, 则服务端取不到值 requests.post(url='', data={'':1,}, headers={ 'content-type':'application/json' })
2、post传参类型
在通过requests.post()进行POST请求时,传入报文的参数有两个,一个是data,一个是json。
两者的区别:
①data为dict时如果不指定content-type,默认为application/x-www-form-urlencoded
②data为str时如果不指定content-type,默认为text/plain
③json无论为dict还是str,如果不指定content-type,默认application/json
常见的form表单可以直接使用data参数进行报文提交,而data的对象则是python中的字典类型;
而在最新爬虫的过程中遇到了一种payload报文,是一种json格式的报文,因此传入的报文对象也应该是格式的;这里有两种方法进行报文提交:
常见的form表单可以直接使用data参数进行报文提交,而data的对象则是python中的字典类型;
而在最新爬虫的过程中遇到了一种payload报文,是一种json格式的报文,因此传入的报文对象也应该是格式的;这里有两种方法进行报文提交:
import requests import json url = "http://example.com" data = { 'a': 1, 'b': 2, } # 1、 requests.post(url, data=json.dumps(data)) # 2、json参数会自动将字典类型的对象转换为json格式 requests.post(url, json=data)
3、注意
requests.post(url='xxxxxxxx', data={'xxx':'yyy'}) #没有指定请求头,#默认的请求头:application/x-www-form-urlencoed #如果我们自定义请求头是application/json,并且用data传值, 则服务端取不到值 requests.post(url='', data={'':1,}, headers={ 'content-type':'application/json' }) requests.post(url='', json={'':1,}, ) #默认的请求头:application/json
三、响应response
1、响应消息体的四种返回格式:
| 返回格式 | 说明 | 用处 |
| r.text | 返回字符串类型 | 获取网页HTML时用 |
| r.content | 返回字节类型 | 下载图片或文件时用 |
| r.json | 返回字典格式 | 明确服务器返回json数据才能用 |
| r.raw | 返回原始格式 |
2、response对象的属性
import requests respone=requests.get('http://www.jianshu.com') # respone属性 print(respone.text) #字符串类型的响应体 print(respone.content) #字节类型的响应体
print(respone.iter_content) # 字节类型的响应体(迭代器对象) print(respone.status_code) #响应状态码 print(respone.headers) #响应头 print(respone.cookies) #响应cookies(字符串类型) print(respone.cookies.get_dict()) #响应cookie(字典类型) print(respone.cookies.items()) print(respone.url) print(respone.history) # 重定向之前的地址 (列表类型) print(respone.encoding) #查看响应内容的编码格式
3、修改响应内容的编码
#编码问题 import requests res=requests.get('http://www.baidu.com') #修改响应内容编码格式 #res.apparent_encoding 获取网站编码格式,赋值给res.encoding(默认utf-8) res.encoding=res.apparent_encoding
4、response转换成json格式
#解析json import requests response=requests.get('http://httpbin.org/get') import json res1=json.loads(response.text) #太麻烦 res2=response.json() #直接获取json数据
5、使用代理
#代理设置:先发送请求给代理,然后由代理帮忙发送(封ip是常见的事情) import requests proxies={ 'http':'http://egon:123@localhost:9743',#带用户名密码的代理,@符号前是用户名与密码 'http':'http://localhost:9743', #前面的http是代理类型,后面的是代理地址(IP和端口) 'https':'https://localhost:9743', } respone=requests.get('https://www.12306.cn', proxies=proxies)
6、超时设置
#超时设置 #两种超时:float or tuple #timeout=0.1 #代表接收数据的超时时间 #timeout=(0.1,0.2)#0.1代表链接超时 0.2代表接收数据的超时时间 import requests respone=requests.get('https://www.baidu.com', timeout=0.0001)
7、异常处理
#异常处理 try: r=requests.get('http://www.baidu.com',timeout=0.00001) except Exception as e: print('e')
8、上传文件
import requests files={'file':open('a.jpg','rb')} #key是文件名称,value是文件对象 respone=requests.post('http://httpbin.org/post',files=files)

浙公网安备 33010602011771号