selenium案例——爬取哔哩哔哩排行榜

案例需求:

1.使用selenium自动化爬虫爬取哔哩哔哩排行榜中舞蹈类的数据(包括视频标题、up主、播放量和评论量)

2.利用bs4进行数据解析和提取

3.将爬取的数据保存在本地json文件中

4.保存在excel文件中

分析:

1.请求url地址:https://www.bilibili.com/v/popular/rank/dance

2.加载等待事件,否则获取数据不充分

复制代码
wait = WebDriverWait(self.browsers, 280)
wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'rank-item')))
time.sleep(5)

3.获取相应内容

复制代码
last_height = self.browsers.execute_script("return document.body.scrollHeight")
while True:
    self.browsers.execute_script('window.scrollTo(0, document.body.scrollHeight);')
    time.sleep(5)
    data = self.browsers.page_source  # 获取网页源码
    self.parse_data(data=data)
    new_height = self.browsers.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

4.使用bs4解析数据

复制代码
soup = BeautifulSoup(data, 'lxml')
titles = soup.select('.info .title')  # 标题
up_names = soup.select('.info .up-name')  # up主
# :nth-of-type(2) 用于选择指定类型的第二个元素
play_counts = soup.select('.info .detail-state .data-box:nth-of-type(1)')  # 播放量
comment_counts = soup.select('.info .detail-state .data-box:nth-of-type(2)') # 评论量
rank_data = {}
print(len(titles))
for title, name, play_count, comment_count in zip(titles, up_names, play_counts, comment_counts):
    t = title.get_text().strip()
    n = name.get_text().strip()
    p = play_count.get_text().strip()
    c = comment_count.get_text().strip()
    print('标题:', t)
    print('up主:', n)
    print('播放量:', p)
    print('评论量:', c)
    print('==========================')

5.保存在本地json文件中

复制代码
with open('rank_data.json', 'a', encoding='utf-8') as f:
    f.write(json.dumps(rank_data, ensure_ascii=False) + '\n')

6.保存在excel文件中

复制代码
wb =workbook.Workbook()#创建一个EXcel对象 就相当于是要生成一个excel 程序
ws = wb.active #激活当前表
ws.append(['标题','up主','播放量','评论量'])
复制代码
#保存数据
def save_data(self,title,name,paly,comment):
    ws.append([title,name,paly,comment])
    # 保存为Excel数据
    wb.save('哔哩哔哩排行榜数据.xlsx')

案例代码:

复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
from openpyxl import workbook #第三方模块 需要安装
import time
import json

wb =workbook.Workbook()#创建一个EXcel对象 就相当于是要生成一个excel 程序
ws = wb.active #激活当前表
ws.append(['标题','up主','播放量','评论量'])

class Spider:
    def __init__(self):
        self.url = 'https://www.bilibili.com/v/popular/rank/dance'
        self.options = webdriver.ChromeOptions()
        self.options.add_experimental_option('excludeSwitches', ['enable-automation'])
        self.browsers = webdriver.Chrome(options=self.options)

    # 访问哔哩哔哩排行榜
    def get_bili(self):
        self.browsers.get(self.url)
        wait = WebDriverWait(self.browsers, 280)
        wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'rank-item')))
        time.sleep(5)

    # 获取响应内容
    def get_data(self):
        last_height = self.browsers.execute_script("return document.body.scrollHeight")
        while True:
            self.browsers.execute_script('window.scrollTo(0, document.body.scrollHeight);')
            time.sleep(5)
            data = self.browsers.page_source  # 获取网页源码
            self.parse_data(data=data)
            new_height = self.browsers.execute_script("return document.body.scrollHeight")
            if new_height == last_height:
                break
            last_height = new_height

    # 解析信息
    def parse_data(self, data):
        soup = BeautifulSoup(data, 'lxml')
        titles = soup.select('.info .title')  # 标题
        up_names = soup.select('.info .up-name')  # up主
        # :nth-of-type(2) 用于选择指定类型的第二个元素
        play_counts = soup.select('.info .detail-state .data-box:nth-of-type(1)')  # 播放量
        comment_counts = soup.select('.info .detail-state .data-box:nth-of-type(2)') # 评论量
        rank_data = {}
        print(len(titles))
        for title, name, play_count, comment_count in zip(titles, up_names, play_counts, comment_counts):
            t = title.get_text().strip()
            n = name.get_text().strip()
            p = play_count.get_text().strip()
            c = comment_count.get_text().strip()
            print('标题:', t)
            print('up主:', n)
            print('播放量:', p)
            print('评论量:', c)
            print('==========================')
            self.save_data(t,n,p,c)
            rank_data['标题'] = t
            rank_data['up主'] = n
            rank_data['播放量'] = p
            rank_data['评论量'] = c
            with open('rank_data.json', 'a', encoding='utf-8') as f:
                f.write(json.dumps(rank_data, ensure_ascii=False) + '\n')
    #保存数据
    def save_data(self,title,name,paly,comment):
        ws.append([title,name,paly,comment])
        # 保存为Excel数据
        wb.save('哔哩哔哩排行榜数据.xlsx')

if __name__ == '__main__':
    s = Spider()
    s.get_bili()
    s.get_data()

运行结果:

相关推荐
vx_biyesheji000131 分钟前
豆瓣电影推荐系统 | Python Django 协同过滤 Echarts可视化 深度学习 大数据 毕业设计源码
大数据·爬虫·python·深度学习·django·毕业设计·echarts
深蓝电商API1 小时前
爬虫IP封禁后的自动切换与检测机制
爬虫·python
喵手3 小时前
Python爬虫实战:公共自行车站点智能采集系统 - 从零构建生产级爬虫的完整实战(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集公共自行车站点·公共自行车站点智能采集系统·采集公共自行车站点导出csv
喵手3 小时前
Python爬虫实战:地图 POI + 行政区反查实战 - 商圈热力数据准备完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·地区poi·行政区反查·商圈热力数据采集
芷栀夏3 小时前
从 CANN 开源项目看现代爬虫架构的演进:轻量、智能与统一
人工智能·爬虫·架构·开源·cann
辣香牛肉面4 小时前
Wireshark v4.6.2 开源免费网络嗅探抓包工具中文便携版
网络·测试工具·wireshark
喵手19 小时前
Python爬虫实战:HTTP缓存系统深度实战 — ETag、Last-Modified与requests-cache完全指南(附SQLite持久化存储)!
爬虫·python·爬虫实战·http缓存·etag·零基础python爬虫教学·requests-cache
喵手19 小时前
Python爬虫实战:容器化与定时调度实战 - Docker + Cron + 日志轮转 + 失败重试完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·容器化·零基础python爬虫教学·csv导出·定时调度
测试工程师成长之路21 小时前
Serenity BDD 框架:Java + Selenium 全面指南(2026 最新)
java·开发语言·selenium
may_一一21 小时前
xpath定位:selenium和playwrightAnt Design / 表单类页面)
selenium·测试工具