解决python爬虫抖音视频翻页问题
在爬取抖音博主全部视频时,遇到翻页问题,如何通过程序自动完成翻页并加载后续视频链接?
翻页方式
抖音视频翻页有两种方式:
页码索引(page index):例如:https://segmentfault.com/u/ponponon/articles
最大 id(max_id):例如:https://segmentfault.com/questions/subscribed
解决方法
使用最大 id 方式实现翻页:
获取初始页面中的视频链接后,提取页面中最新的视频 id(max_id)。
AI抖音
AI抖音,会思考的抖音
下载
在随后的请求中,将 max_id 作为查询参数,获取下一页的视频链接。
不断重复此过程,直到获取所有视频链接。
代码实现
在你的代码中,在 get_video_url() 函数中添加以下内容:
这样,代码将自动翻页,并获取该抖音博主全部视频链接。
if not video_url:
return
max_id = None
while True:
try:
url_new = 'https://www.douyin.com/user/MS4wLjABAAAAp3rtDfotN7-mHjDIr0XR2XJ5g0C1DIVAuJYgBHJYX-xJLZgoHvfN0r0yAWTLybn7'
if max_id:
url_new += f'?max_cursor={max_id}'
r = requests.get(url=url_new, headers=headers)
html = BeautifulSoup(r.text, 'html.parser')
result = html.find_all('a', 'B3AsdZT9 chmb2GX8 UwG3qaZV')
if not result:
print("Finished")
break
for item in result:
get_video(item['href'])
max_id = item['href'][-19:]
except Exception as e:
print("解析失败")
print(e)
break