10、爬虫-requests的使用-session()、防盗链

#会话-cookie的使用

requests.session()

"""
先登录网站、找到llogin相关的url 得到cookie、拿到format Data中的信息
带着cookie去请求url
使用cookie去访问(session-会话)该网站其它内容的时候都会带着cookie
"""

import requests

#创建会话
session = requests.session()
#用户的登录信息
headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Cookie:":"_uab_collina=170453738541714545106624; JSESSIONID=5A020EC4AD7C575B147D2B3FEDB2DF65; guidesStatus=off; highContrastMode=defaltMode; cursorStatus=off; BIGipServerpassport=820510986.50215.0000; route=c5c62a339e7744272a54643b3be5bf64; BIGipServerotn=2145911050.24610.0000"
}

#这是payload里的form Data参数
data = {
    "randCode": "409615",
    "username": "18289412452",
    "password": "@k2oOLSlRNqh2M1wq92gu2g==",
    "appid": "otn"
}

#登录页面的url
url = "https://kyfw.12306.cn/passport/web/login"

#使用post方式请求网站、并带上参数、这里使用session.post 请求的时候 保存了会话信息、下次在请求该网站的内容的时候就不需要cookies了
response = session.post(url,data=data)
#获取登录信息
print(response.text)
#获取cookie
#response.cookies

#在使用上面的session去请求网站内的其他内容,可以不用在登录
response2 = session.get("http://xxxx")
print(response2.json())

#上面的第二步相当于、带上cookie去请求
requests.get("http://xxxx", headers=headers)

 

防盗链:Referer

概念:追溯到上一级链接、从当前等级的上一级链接

案例:下载视频

"""
爬取视频

视频的下载链接
https://video.pearvideo.com/mp4/short/20210630/cont-1733706-15707553-hd.mp4

#视频XHR获取的链接
videoStatusUrl = "https://www.pearvideo.com/videoStatus.jsp?contId=1733706&mrd=0.500048304867837"       #headers中的Request URL:
srcUrl = "https://video.pearvideo.com/mp4/short/20210630/1705128822506-15707553-hd.mp4"         #Previwe中的srcurl

#视频的网页链接
url = "https://www.pearvideo.com/video_1733706"

可以看到:下载的原链接 cont-1733706-15707553 是关键项
将srcurl中的 1705128639745 替换为 url中的1733706 加上cont即可获得一个完整的下载链接:cont-1733706
"""
import requests

headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",

    #防盗链
    "Referer":"https://www.pearvideo.com/video_1733706"
}

#视频的网页链接
url = "https://www.pearvideo.com/video_1733706"


#将url中的video编码1733706提出来
cont_id = url.split("_")[1]

#将拿到的cont_id拼接到srcurl中
srcurl=f"https://www.pearvideo.com/videoStatus.jsp?contId={cont_id}&mrd=0.500048304867837"

#获取视频下载链接中带有下载地址的json
response = requests.get(srcurl,headers=headers)
#print(response.json())

#从json中获取需要的字段元素、srcurl和systemTime
dic = response.json()   #保存在字典中
systemtime = dic["systemTime"]
srcUrl = dic["videoInfo"]["videos"]["srcUrl"]

#拼接下载链接
vedio_link = srcUrl.replace(systemtime, f"cont-{cont_id}")
#print(vedio_link)

#下载视频
with open("F:\\a.mp4", "wb") as file:
    file.write(requests.get(vedio_link).content)
posted @ 2024-07-01 22:25  little小新  阅读(3)  评论(0编辑  收藏  举报