首页 > 其他分享 >7.10 requests的高级使用

7.10 requests的高级使用

时间:2023-07-10 21:22:30浏览次数:35  
标签:7.10 get res 高级 print http requests response

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': '[email protected]',
'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('[email protected]' 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)

标签:7.10,get,res,高级,print,http,requests,response
From: https://www.cnblogs.com/abc683871/p/17542322.html

相关文章

  • 7.10日
    好好好,晚上又在想七想八,因为自己的不努力再次感到焦虑,不只是眼前,还有对未来的迷茫。今天的天气十分炎热,我在家里摸鱼了一整天。早上起来后,我打开电脑,打开了一款游戏。本来想着只玩一会儿,结果不知不觉就玩了两个小时。中午时分,我又点开了一个视频网站,看了几个小时的综艺节目。下......
  • 暑假周记(7.10)
    今天周一哇去,给两个年纪小孩上英语,还有一个小升初教语数英好累啊,哇,那些乡村支教的老师们是怎么做到的,我这个还是有着不错的工资的,我的上课条件也远比他们优越,感念这一帮伟大的老师,今天忙了一天就看了十页大道至简,倒是第一次玩游戏用上Java了----我的世界Java版本,Java真牛,一定得把......
  • 7.10
    #include<iostream>#include<cmath>usingnamespacestd;typedeflonglongll;intstart,len;//序列开始因子和连续因子个数intmain(){cin.tie(0);llN;cin>>N;intstart=0,len=0;for(inti=2;i<=sqrt(N);i++)......
  • 7.10
    九、内部类详解9.1实例内部类当一个事物的内部,还有一个部分需要一个完整的结构进行描述,而这个内部的完整的结构又只为外部事物提供服务(内部类就相当于公司的每一个部门,少了哪一个部门,就去定义那一个部门,而外部类就相当于整个公司)。在Java中,可以将一个类定义在另一个类或者一......
  • 云原生周刊:Dapr 完成模糊测试审计 | 2023.7.10
    开源项目推荐Shell-operatorShell-operator是一个在Kubernetes集群中运行事件驱动脚本的工具。node-problem-detectornode-problem-detector旨在使集群管理堆栈中的上游层可以看到各种节点问题。它是一个在每个节点上运行的守护进程,检测节点问题并将其报告给apiserver。......
  • 2023.7.10
    1importjava.util.Scanner;23publicclasstest4{5publicstaticvoidmain(String[]args)6{7inti=0;8intsum=0;910while(i<100)11{12i++;13sum=sum+......
  • python高级语法笔记
    5.python高级一/demo03_python环境变量路径.pyfromloguruimportloggerimportsyssys.path.append('/Users/toby/Downloads/PythonAdvanced/code/pythonAdvanced5Verify')forpathinsys.path:logger.debug(path)5.python高级一/demo09_xxxsetter和xxxdeleter装饰......
  • 高级编程技巧揭秘!精通Python装饰器,打造灵活强大的代码结构!
    装饰器是Python中一种强大而灵活的编程技巧,它可以用于修改或扩展函数的行为,同时又不需要修改函数的源代码。本文将介绍Python中的装饰器的基本概念、使用方法以及高级技巧,帮助你从入门到精通装饰器的使用。一、基本概念在深入学习装饰器之前,我们首先需要了解一些基本概念。1.1......
  • vue高级
    vue高级vue脚手架我们可以使用VueCLI来创建vue脚手架项目VueCLI官方文档安装vue/clinpminstall-g@vue/cli#或yarnglobaladd@vue/clivue--version#或vue-V#升级npmupdate-g@vue/cli#或者yarnglobalupgrade--latest@vue/cli创建一个vue项目#......
  • ,软件运行监听地址 ,扫码登录,爬虫介绍,requests模块介绍和快速使用,get请求携带参数,编码
    补充#软件运行,监听地址127.0.0.1 只能访问127.0.0.1localhost不能用本机ip地址访问,外部所有人都不能访问你0.0.0.0 127.0.0.1localhost本机ip地址访问同一个局域网内,都可以通过ip地址访问#本地host解析 输入网址---》www.baidu.com---->找本地host文......