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

news/2024/10/18 7:23:35/

案例需求:

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

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

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

4.保存在excel文件中

分析:

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

b6b20cf86cd1420faabfbda447086cd3.png

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:breaklast_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 jsonwb =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:breaklast_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['标题'] = trank_data['up主'] = nrank_data['播放量'] = prank_data['评论量'] = cwith 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()

运行结果:

5abf89ee4853433b8ecc1a48f21da997.png

cbfa7daafb1046e4bd36bc338176cbd3.png

aa5d35c7398548eeb09ea5b1f04b53e9.png 

 


http://www.ppmy.cn/news/1539933.html

相关文章

ts 中 namespace 作用

一、组织代码和避免命名冲突 1. 代码组织 命名空间允许你将相关的代码分组在一起,使代码结构更加清晰和易于理解。 namespace MathUtils {export function add(a: number, b: number): number {return a b;}export function subtract(a: number, b: number): nu…

根据json转HttpClient脚本

String json “{\n” " “paths”: {\n" " “/dev-api/system/subjectResult/exportUserList”: {\n" " “post”: {\n" " “tags”: [\n" " “bd-subject-result-controller”\n" " ],\n" " “summ…

【数据结构与算法】栈和队列(下)

记录自己所学&#xff0c;无详细讲解 队列的实现--使用动态链表 1.项目目录文件 、 2.头文件 queue.h #pragma once #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <stdbool.h> struct QueueNode {int data;struct Queue…

软件框架和软件架构的概念

软件框架&#xff08;Software Framework&#xff09; 和 软件架构&#xff08;Software Architecture&#xff09; 的关系在于它们分别处于系统设计和实现的不同层次&#xff0c;互为补充。架构决定了系统的整体结构和设计&#xff0c;而框架则是实现这些设计的工具和技术。下…

BMC 中的日志类型:Audit Log、SEL Log、Sys Log 与 SOL Log 的功能与区别

在现代服务器和数据中心管理中&#xff0c;BMC&#xff08;Baseboard Management Controller&#xff09;作为一种关键的管理组件&#xff0c;负责监控和管理硬件设备的状态。为了确保系统的安全性和操作的可追溯性&#xff0c;BMC 提供了多种类型的日志&#xff0c;以记录不同…

C++算法练习-day5——59.螺旋矩阵2

题目来源&#xff1a;. - 力扣&#xff08;LeetCode&#xff09; 题目思路分析 给定一个整数 n&#xff0c;要求生成一个 n x n 的矩阵&#xff0c;其中的元素按螺旋顺序排列&#xff0c;从矩阵的左上角开始&#xff0c;向右、向下、向左、向上依次填充&#xff0c;直到所有元…

PROFINET开发EtherNet/IP开发Vline板卡在称重设备行业的应用

本次分享的&#xff0c;是我们VlinePROFINET开发EtherNet/IP开发嵌入式板卡在称重行业的典型应用。 应用背景 在现代科技高度发达的时代&#xff0c;无论是科学研究、医疗诊断、制药生产还是工业制造&#xff0c;准确的测量和称重都是保证质量和效率的关键。 随着新项目实施…

JavaWeb 22.Node.js_简介和安装

有时候&#xff0c;后退原来是向前 —— 24.10.7 一、什么是Node.js Node.js 是一个于 Chrome V8 的 JavaScript 运行时环境&#xff0c;可以使 JavaScript 运行在服务器端。使用 Node.js&#xff0c;可以方便地开发服务器端应用程序&#xff0c;如 Web 应用、API、后端服务&a…