1.requests概念
Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用。
2.为什么使用requests
与urllib的区别,urllib的缺点
-
手动处理url编码
-
手动处理post请求参数
-
处理cookie和代理操作繁琐
requests模块有点:
-
自动处理url编码
-
自动处理post请求参数
-
简化cookie和代理操作
3.requests安装
pip install requests
使用基本流程:
-
指定url
-
基于requests模块发起请求
-
获取响应对象中的数据值
-
持久化存储
二、requests的请求
User-Agent
请求载体身份标识的伪装:
-
User-Agent:请求载体身份标识,通过浏览器发起的请求,请求载体为浏览器,则该请求的User-Agent为浏览器的身份标识,使用爬虫程序发起的请求,则该请求的载体为爬虫程序,则该请求的User-Agent为爬虫程序的身份标识。可以通过判断该值来获知该请求的载体究竟是基于哪款浏览器还是基于爬虫程序。
-
反爬机制:某些门户网站会对访问该网站的请求中的User-Agent进行捕获和判断,如果该请求的UA为爬虫程序,则拒绝向该请求提供数据。
-
反反爬策略:将爬虫程序的UA伪装成某一款浏览器的身份标识。
1.requests基于get请求
1.简单的get请求
import requests response=requests.get('http:/www.baidu.com/') print(response.text)
2.带参数的GET请求-->headers
通常我们在发送请求时都需要带上请求头,请求头是将自身伪装成浏览器的关键,常见的有用的请求头如下:
-
Host
-
Referer:大型网站通常都会根据该参数判断请求的来源
-
User-Agent:客户端
-
Cookie:Cookie信息虽然包含在请求头里,但requests模块有单独的参数来处理他,headers={}内就不要放它了
url = "https://www.sogou.com/web" # 设定动态的请求参数 wd = input("enter a key word:") params = { "query":wd } # UA伪装 headers = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36" } # 参数2:params是一个字典,用来处理动态请求参数 response = requests.get(url=url,params=params,headers=headers) # 修改原始的编码格式 response.encoding = "utf-8" page_text = response.text fileName = wd + ".html" with open(fileName,"w",encoding="utf-8") as fp: fp.write(page_text) print(fileName,"下载成功!")
3.带参数的GET请求-->params
1.自己拼接GET参数
# 在请求头内将自己伪装成浏览器,否则百度不会正常返回页面内容 import requests headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36', } response=requests.get('https://www.baidu.com/s?wd=python&pn=1',headers=headers) print(response.text) # 如果查询关键词是中文或者有其他特殊符号,则不得不进行url编码 from urllib.parse import urlencode wb = "熊大" encode_res = urlencode({"k":wb},encoding="utf-8") print(encode_res) #k=haiyan%E6%B5%B7%E7%87%95 keywords = encode_res.split("=")[1] #haiyan%E6%B5%B7%E7%87%95 url = "https://www.baidu.com/s?wd=%s&pn=1"%(keywords) # url = "https://www.baidu.com/s?"+encode_res print(url) # 然后拼接成url response = requests.get( url, headers =headers )
2.url中传递params参数
url = "https://www.sogou.com/web" # 设定动态的请求参数 wd = input("enter a key word:") params = { "query":wd } # UA伪装 headers = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36" } # 参数2:params是一个字典,用来处理动态请求参数 response = requests.get(url=url,params=params,headers=headers) # 修改原始的编码格式 response.encoding = "utf-8" page_text = response.text fileName = wd + ".html" # 保存到本地文件 with open(fileName,"w",encoding="utf-8") as fp: fp.write(page_text) print(fileName,"下载成功!")
4.带参数的GET请求-->cookies
登录github,然后从浏览器中获取cookies,以后就可以直接拿着cookie登录了,无需输入用户名密码。
# 用户名:egonlin 邮箱[email protected] 密码lhf@123 import requests Cookies={ 'user_session':'wGMHFJKgDcmRIVvcA14_Wrt_3xaUyJNsBnPbYzEL6L0bHcfc', } response=requests.get('https://github.com/settings/emails', cookies=Cookies) #github对请求头没有什么限制,我们无需定制user-agent,对于其他网站可能还需要定制 print('[email protected]' in response.text) # True
2.requests基于post请求
与get请求的区别:
get请求:
-
没有请求体
-
数据必须在1K之内!
-
GET请求数据会暴露在浏览器的地址栏中
post请求:
-
数据不会出现在地址栏中
-
数据的大小没有上限
-
有请求体
-
请求体中如果存在中文,会使用URL编码!
1.简单的post请求
import requests response=requests.get('http:/www.baidu.com/') print(response.text)
2.带参数的post请求-->data
post请求的数据在form-data中,可以获取请求中的form-data数据,根据我们的需求改动数据,发起请求。
url = "https://movie.douban.com/j/chart/top_list" num = 200 for i in range(0,num,20): start = i data = { "type": "24", "interval_id": "100:90", "action": "", "start": i, "limit": "20" } response = requests.post(url=url,data=data,headers=headers) for movie in response.json(): print(movie["rank"],movie["title"],movie["score"])
3.post请求模拟登陆
post请求登录:
-
对于登录来说,应该输错用户名或密码然后分析抓包流程,用脑子想一想,输对了浏览器就跳转了,还分析个毛线,累死你也找不到包
-
要做登录的时候一定记得要把cookie先清除;
-
requests.session():中间的cookie都不用自己分析了,有用的没用的都给放进来了、
-
response.cookie.get_dict() #获取cookie
自动登录github代码
1.目标站点分析
-
然后输入错误的账号密码,抓包
-
发现登录行为是post提交到:https://github.com/session
-
而且请求头包含cookie
-
而且请求体包含:
commit:Sign in
utf8:✓
authenticity_token:lbI8IJCwGslZS8qJPnof5e7ZkCoSoMn6jmDTsL1r/m06NLyIbw7vCrpwrFAPzHMep3Tmf/TSJVoXWrvDZaVwxQ==
login:egonlin
password:123
2.流程分析:
-
先GET:https://github.com/login拿到初始cookie与authenticity_token
-
返回POST:https://github.com/session, 带上初始cookie,带上请求体(authenticity_token,用户名,密码等)
-
最后拿到登录cookie
ps:如果密码时密文形式,则可以先输错账号,输对密码,然后到浏览器中拿到加密后的密码,github的密码是明文
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() #第三次请求:以后的登录,拿着login_cookie就可以,比如访问一些个人配置 r3=requests.get('https://github.com/settings/emails',cookies=login_cookie) print('[email protected]' in r3.text) #True
三、响应对象Response
1.response对象的属性
import requests respone=requests.get('http://www.jianshu.com')
response属性:
-
text:字符串的文本内容
-
content:二进制byte格式的内容
-
status_code:响应的状态码
-
cookies:请求的cookie数据
-
encoding:响应体的编码格式
-
cookies.get_dict():请求cookies的字典
-
url:请求的的url
-
json():请求数据为json时,返回json字典