7.10 requests的高级使用

发布时间 2023-07-10 21:21:08作者: ranbo145

1.  自动携带cookie和session对象

header={
'Referer':
'http://www.aa7a.cn/user.php?&ref=http%3A%2F%2Fwww.aa7a.cn%2F',
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}
data={
'username': '616564099@qq.com',
'password': 'lqz123',
'captcha': '1111',
'remember': 1,
'ref': 'http://www.aa7a.cn/',
'act': 'act_login',
}

session = requests.session() # 添加session对象
res = session.post('http://www.aa7a.cn/user.php',headers=header,data=data)
cookie = res.cookies.get_dict() # 转为字典
print(type(cookie))
res1 = session.get('http://www.aa7a.cn/') # 不需要再像之前那样手动携带cookies=cookie
print('616564099@qq.com' in res1.text)

2.响应对象response

# http响应,就是res对象,所以http响应的东西,都在这个对象中
response = requests.get('http://www.aa7a.cn/')
print(type(response))

from requests.models import Response
print(response.text)   # 响应体转成字符串,默认使用utf-8编码----》以后打印出来可能会乱码
print(response.content) # 响应体的bytes格式
print(response.status_code)#响应状态码
print(response.headers)  # 响应头
print(response.cookies)  # cookie
print(response.cookies.get_dict()) # cookie 转成字典
print(response.cookies.items()) # 键值对的形式
print(response.url)    # 请求地址
print(response.history) # 访问一个地址,如果重定向了,requests会自动重定向过去,放着之前没重定向之前的地址,列表
print(response.encoding)  # 网页编码

# 关闭response:response.close()
response.iter_content()

3.从网站上爬取图片和视频进行下载

# 下载图片
res = requests.get('https://c.53326.com/d/file/lan20191114/rmiuuvwbjjc.jpg')
with open('pg3.png','wb') as f:
    # 第一种方法
    f.write(res.content)
    # 第两种方法 (可迭代的方法)之后用这种
    for line in res.iter_content(chunk_size=1024): # chunk_size指定一次性拿多少字节
        f.write(line)

# 下载视频
res = requests.get('https://video.pearvideo.com/mp4/adshort/20181025/cont-1463007-13121718_adpkg-ad_hd.mp4')
with open('男子自己造飞机.mp4','wb') as f:
    for line in res.iter_content(chunk_size=1024):
        f.write(line)

 4.编码问题

# 直接打印res.text 字符串形式----->从网络过来是二进制---->转成字符串涉及到编码--->默认以utf-8--->现在会自动识别页面的编码,自动转成对应的
res.encoding='gbk' # 手动指定编码
print(res.text)

5.解析json 返回html内容

res=requests.post('http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword',data='cname=&pid=&keyword=%E5%91%A8%E6%B5%A6&pageIndex=1&pageSize=10', # data等于请求体的内容
                  headers={
                  'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'})
print(res.text)

res1 = requests.post('http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword', data={
    'cname': '',
    'pid': '',
    'keyword': '周浦',
    'pageIndex': 1,
    'pageSize': 10,
})
print(res1.text) # 拿到的都是字符串格式
print(res1.json()['Table1']) # json转为字典模式 可以通过中括号取值

for item in res1.json()['Table1']: # 循环取值打印出来
    print('餐厅名字:%s,餐厅地址:%s'%(item['storeName'],item['addressDetail']))

6.ssl认证

# 发送https请求 通常需要携带证书 所以我们拿出证书携带发送
res = requests.get('https://www.cnblogs.com/liuqingzheng/p/16005866.html',verify=False)
print(res.text)
res1 = requests.get('https://www.12306.cn',
                    cert=('/path/server.crt', # 证书
                          '/path/key') # 组成是路径和秘钥
                          )
print(res1.text)

7.使用代理ip 

我们验证是否走了代理,需要我们自己搭建一个django框架,运行自己的服务

# 我们通过代理来发送请求
import requests
proxies = {
    'http': '36.6.145.45',
}
respone=requests.get('http://127.0.0.1:8000/',proxies=proxies)
print(respone)

在我们创建的django的views.py中

from django.shortcuts import render, HttpResponse

def index(request):
    ip = request.META.get('REMOTE_ADDR')
    print(ip)
    return HttpResponse('您的ip是:%s' % ip)

然后在url中添加路由

8.超时设置

import requests
respone=requests.get('https://www.cnblogs.com/abc683871/',timeout=1) # 超过1s就会报异常
print(respone)

9.异常处理

import requests
from requests.exceptions import * #可以查看requests.exceptions获取异常类型

try:
    r=requests.get('http://www.baidu.com',timeout=0.00001)
except ReadTimeout:
    print('===:')
# except ConnectionError: #网络不通
#     print('-----')
# except Timeout:
#     print('aaaaa')

except RequestException:
    print('Error')

10.上传文件

通过requests请求讲图片上传

import requests
files = {'myfile':open('pg.png','rb')}
response = requests.post('http://127.0.0.1:8000/upload/',files=files)
print(response.status_code)