首页 > 其他分享 >请求库之requests库

请求库之requests库

时间:2022-09-24 16:23:01浏览次数:45  
标签:请求 get session cookie requests com

目录

一、介绍

#介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3)

#注意:requests库发送请求将网页内容下载下来以后,并不会执行js代码,这需要我们自己分析目标站点然后发起新的request请求

#安装: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、基本请求**

response是python的对象,包含响应头,响应体......

header = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
    'referer': 'https://www.mzitu.com/225078/2'
 }

response = requests.get('https://www.mzitu.com/', headers=header)
print(response.text)  # 响应的文本内容-->解析出图片地址

result = requests.get('https://i3.mmzztt.com/2020/03/14a02.jpg', headers=header)
print(result.content)  # 响应的二进制内容

# 下载并保存图片
with open('a.jpg', 'wb')as f:
   for line in result.iter_content():
       f.write(line)
**2、带参数的get请求**

header = {
     'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
    }

方式一:直接拼在url后边
res=requests.get('https://www.baidu.com/s?wd=美女',headers=header)
# 如果查询关键词是中文或者有其他特殊符号,则不得不进行url编码
# from urllib.parse import urlencode,unquote 
编码
urlencode('美女',encoding='utf-8')  
解码
unquote('%2Fs%3Fwd%3D%25E7%') 

方式二:用params, 可以自动url编码
res=requests.get('http://www.baidu.com/s', headers=header, params={'wd':'美女'})
**3、请求携带cookie**

方式一,在header中放
header = {
     'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
     'cookie':'key=asdfasdfasdfsdfsaasdf; key2=asdfasdf; key3=asdfasdf'
     }
res=requests.get(url, headers=header)


方式二,当成参数直接传,推荐
header = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
      }

# cookies是一个字典或者CookieJar对象,第一次访问利用respone.cookies获取CookieJar对象-->赋值给变量,访问其他页面时,传入CookieJar对象
res=requests.get(url, headers=header, cookies{'key':'asdfasdf'})
print(res.text)

三、基于post请求

**1、基本用法**
# requests.post()用法与requests.get()完全一致,特殊的是requests.post()有一个data参数,用来存放请求体数据
# data参数携带数据(urlencoded和json)

res=requests.post(url, data={'name':'lqz'})

res=requests.post(url, json={"age":"18"})

**2、发送post请求,模拟浏览器的登录行为**
一 目标站点分析
    浏览器输入https://github.com/login
    然后输入错误的账号密码,抓包
    发现登录行为是post提交到:https://github.com/session
    请求头包含cookie
    请求体包含:
        commit:Sign in
        utf8:✓
        authenticity_token:lbI8IJCwGslZS8qJPnof5e7ZkCoSoMn6jmDTsL1r/m06NLyIbw7vCrpwrFAPzHMep3Tmf/TSJVoXWrvDZaVwxQ==
        login:egonlin
        password:123


二 流程分析
    先GET:https://github.com/login拿到初始cookie与authenticity_token
    返回POST:https://github.com/session, 带上初始cookie,带上请求体(authenticity_token,用户名,密码等)
    最后拿到登录cookie


ps:如果密码时密文形式,则可以先输错账号,输对密码,然后到浏览器中拿到加密后的密码,github的密码是明文
代码如下
点击查看代码
模拟登录,获取cookie

import requests
import re

#第一次请求
r1=requests.get('https://github.com/login')
r1_cookie=r1.cookies.get_dict() #拿到初始cookie(未被授权)
authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #从页面中拿到CSRF TOKEN

#第二次请求:带着初始cookie和TOKEN发送POST请求给登录页面,带上账号密码
data={
    'commit':'Sign in',
    'utf8':'✓',
    'authenticity_token':authenticity_token,
    'login':'[email protected]',
    'password':'alex3714'
}
r2=requests.post('https://github.com/session',
             data=data,
             cookies=r1_cookie
             )

login_cookie=r2.cookies.get_dict() # 拿到登录后的cookie

#第三次请求:以后的登录,拿着login_cookie就可以,比如访问一些个人配置
r3=requests.get('https://github.com/settings/emails',
                cookies=login_cookie)

print('[email protected]' in r3.text) # 查询邮箱,如果为True,说明cookie已登录
**3、自动携带cookie**
session=requests.session()  # 生成request.session()对象
res1=session.post('http://127.0.0.1:8000/index/')  # 假设这个请求登录了
res2=session.get('http://127.0.0.1:8000/order/')   # 现在不需要手动带cookie,session自动处理

代码如下
点击查看代码
自动携带cookie,简化上述模拟登录案例

import requests
import re

session=requests.session()
#第一次请求
r1=session.get('https://github.com/login')
authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #从页面中拿到CSRF TOKEN

#第二次请求
data={
    'commit':'Sign in',
    'utf8':'✓',
    'authenticity_token':authenticity_token,
    'login':'[email protected]',
    'password':'alex3714'
}
r2=session.post('https://github.com/session',
             data=data,
             )

#第三次请求
r3=session.get('https://github.com/settings/emails')

print('[email protected]' in r3.text) #True

标签:请求,get,session,cookie,requests,com
From: https://www.cnblogs.com/cqzlei/p/16725417.html

相关文章