1.模拟浏览器登陆
- 登录
- 得到cookie 值
- 带着cookie 去请求目标的 url
- 获取所需的内容
上述操作必须连贯起来,即获取到的cookie 信息必须在本次请求中去使用
💎💎💎在使用request模块的中的 get 或者 post 请求时。每次请求都视为一个新的请求,所以并不能满足上述的连贯,而 cookie 值在每次请求时都会随机生成,所以在通过一次请求得到的 cookie 值,并不能作为下一次请求的 cookie 参数使用。 💎💎💎
session 会话对象
session = request.session()
为解决上述问题,可以使用 session 会话对象,通过该对象,可以使请求都在一次访问中,既可以达到上述的连贯要求。
作用
- 可以进行请求发送
- 如果请求过程中产生了cookie ,则该cookie 值会自动存储,并将值携带在该 session 对象中。
2.需求:对小说网站个人书架内容进行爬取
import requests
if __name__ == '__main__':
session = requests.session()
url = "https://passport.17k.com/ck/user/login"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"
}
data ={
"loginName":"**********",
"password":"**********"
}
session.post(url=url,data=data)
resp = session.get("https://user.17k.com/ck/author/shelf?page=1&appKey=2406394919")
print(resp.json())
注
再对登录请求进行抓包时,请求包中并未出现目标的 url 通过分析,是没有打开 “保留日志”,可以通过打开这个开关,保留请求过程中的登录页面的 url 如下图所示:
梨视频爬取
import requests
import os
if not os.path.exists("梨视频"):
os.mkdir("梨视频")
contId = "https://pearvideo.com/video_1777816".split("_")[1]
url = "https://pearvideo.com/videoStatus.jsp?contId=1777816&mrd=0.6281112342338115"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36",
"Referer": "https://pearvideo.com/video_1777816"
}
resp = requests.get(url=url,headers=headers)
systemtime = resp.json()['systemTime']
src_url= resp.json()['videoInfo']['videos']["srcUrl"]
src_url = src_url.replace(systemtime,f"cont-{contId}")
print(resp.json()['systemTime'])
print(resp.json()['videoInfo']['videos']["srcUrl"])
print(src_url)
resp2 = requests.get(url=src_url,headers=headers)
with open("梨视频/"+contId+".mp4","wb") as fp:
fp.write(resp2.content)
resp.close()
resp2.close()
wb") as fp:
fp.write(resp2.content)
resp.close()
resp2.close()