使用Python的requests库和BeautifulSoup库可以轻松爬取B站视频信息,并通过链接深入爬取更多数据。以下代码示例展示了如何从B站页面获取视频信息,并如何点击进入链接继续爬取其它数据。

import requests
from bs4 import BeautifulSoup

items = []  # 存放每个视频的各个项目
print('正在爬取相关信息……')
for video in videos:
    item = {}  # 每个字典存放每个视频的相关信息
    item['标题'] = video.find('a')['title']  # 获取标签属性
    item['总播放数'] = video.find(class_='bili-video-card__stats--item').get_text()
    item['总弹幕数'] = video.find(class_='bili-video-card__stats--item').get_text()  # 获取NavigableString
    item['发布时间'] = video.find(class_='bili-video-card__info--date').get_text()  # 获取目标路径下的子孙字符串
    item['发布者'] = video.find(class_='bili-video-card__info--author').get_text()
    item['链接'] = video.find('a')['href']  # 获取视频链接

    # 访问链接爬取更多数据
    response = requests.get(item['链接'])
    soup = BeautifulSoup(response.text, 'html.parser')
    item['新数据'] = soup.find(...)

    items.append(item)  # 将该视频的信息添加到列表中

具体步骤如下:

  1. 获取视频链接: 在获取每个视频的相关信息时,可以同时获取视频的链接,例如 item['链接'] = video.find('a')['href']

  2. 访问链接: 使用requests库和BeautifulSoup库访问该链接,例如 response = requests.get(url)soup = BeautifulSoup(response.text, 'html.parser')

  3. 获取新数据: 通过BeautifulSoup解析网页内容,获取需要的数据并添加到字典中,例如 item['新数据'] = soup.find(...)

代码示例中:

  • items 列表用于存放每个视频的信息。
  • video 变量遍历每个视频。
  • item 字典用于存放每个视频的详细信息,包括标题、播放数、弹幕数、发布时间、发布者和链接。
  • 循环中获取视频链接并使用 requestsBeautifulSoup 库访问链接,获取更多数据。
  • 最后将每个视频的信息添加到 items 列表中。

注意:

  • 实际代码需要根据B站页面的结构进行调整,soup.find(...) 需要根据具体的数据进行修改。
  • 爬取网站数据时,需要遵守网站的 robots.txt 协议,避免过度爬取造成服务器负担。
  • 同时,也要注意网站反爬虫机制,例如 IP 限制、验证码等,并采取相应的措施进行应对。
Python爬虫:如何从B站页面获取视频信息并深入爬取

原文地址: https://www.cveoy.top/t/topic/oJMS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录