百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

python爬虫练习selenium+BeautifulSoup,爬b站搜索内容保存excel

off999 2024-12-01 02:18 17 浏览 0 评论

一、简介

前面文章已经介绍了selenium库使用,及浏览器提取信息相关方法。参考:python爬虫之selenium库

现在目标要求,用爬虫通过浏览器,搜索关键词,将搜索到的视频信息存储在excel表中。

二、创建excel表格,以及chrome驱动

n = 1
word = input('请输入要搜索的关键词:')
driver = webdriver.Chrome()
wait = WebDriverWait(driver,10)

excl = xlwt.Workbook(encoding='utf-8', style_compression=0)

sheet = excl.add_sheet('b站视频:'+word, cell_overwrite_ok=True)
sheet.write(0, 0, '名称')
sheet.write(0, 1, 'up主')
sheet.write(0, 2, '播放量')
sheet.write(0, 3, '视频时长')
sheet.write(0, 4, '链接')
sheet.write(0, 5, '发布时间')

三、创建定义搜索函数

里面有button_next 为跳转下一页的功能,之所有不用By.CLASS_NAME定位。看html代码可知

<button class="vui_button vui_pagenation--btn vui_pagenation--btn-side">下一页</button>

class名称很长,而且有空格,如果selenium用By.CLASS_NAME定位,有空格会报错:selenium.common.exceptions.NoSuchElementException: Message: no such element

所以这里用By.CSS_SELECTOR方法定位。

def search():
    driver.get("https://www.bilibili.com/")
    input = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'nav-search-input')))
    button = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'nav-search-btn')))

    input.send_keys(word)
    button.click()
    print('开始搜索:'+word)
    windows = driver.window_handles
    driver.switch_to.window(windows[-1])
    get_source()
    #第1页跳转第2页
    button_next = driver.find_element(By.CSS_SELECTOR,'#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.flex_center.mt_x50.mb_x50 > div > div > button:nth-child(11)')
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.video-list.row > div:nth-child(1) > div > div.bili-video-card__wrap.__scale-wrap')))
    button_next.click()
    get_source()

四、定义跳转下一页函数

这里有调转下一页函数,那为什么在上面搜索函数也有下一页功能,因为分析代码。

#第2页的CSS_SELECTOR路径
#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.flex_center.mt_x50.mb_x50 > div > div > button:nth-child(11)

#后面页面的CSS_SELECTOR路径
#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.flex_center.mt_x50.mb_lg > div > div > button:nth-child(11)

第1页的CSS_SELECTOR和后面的页面的CSS_SELECTOR的不一样,所以把第1页跳第2页单独加在了上面搜索函数中。

def next_page():
    button_next = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.flex_center.mt_x50.mb_lg > div > div > button:nth-child(11)')))
    button_next.click()
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.video-list.row > div:nth-child(1) > div > div.bili-video-card__wrap.__scale-wrap')))
    get_source()

五、定义获取页面代码函数

上面定义的函数都有get_source()函数,这个函数就是现在需要创建的,用途获取页面代码,传入BeautifulSoup

def get_source():
    html = driver.page_source
    soup = BeautifulSoup(html, 'lxml')
    save_excl(soup)

六、获取元素并存到excel表

通过BeautifulSoup循环获取页面信息,并存到创建好的excel表中。

def save_excl(soup):
    list = soup.find(class_='video-list row').find_all(class_="bili-video-card")
    for item in list:
        # print(item)
        video_name = item.find(class_='bili-video-card__info--tit').text
        video_up = item.find(class_='bili-video-card__info--author').string
        video_date = item.find(class_='bili-video-card__info--date').string
        video_play = item.find(class_='bili-video-card__stats--item').text
        video_times = item.find(class_='bili-video-card__stats__duration').string
        video_link = item.find('a')['href'].replace('//', 'https://')
        print(video_name, video_up, video_play, video_times, video_link, video_date)

        global n

        sheet.write(n, 0, video_name)
        sheet.write(n, 1, video_up)
        sheet.write(n, 2, video_play)
        sheet.write(n, 3, video_times)
        sheet.write(n, 4, video_link)
        sheet.write(n, 5, video_date)

        n = n +1

七、定义main函数,循环获取跳转每一页

这里默认是10页的数据,后面就不获取了,可以自行调整页面数。最后保存表名。

def main():
    search()
    for i in range(1,10):
        next_page()
        i = i + 1
    driver.close()
if __name__ == '__main__':
    main()
    excl.save('b站'+word+'视频.xls')

八、最终代码执行效果

这里CSS_SELECTOR路径,我这里尽量的在最底层,所以比较长,因为短路径,经常性等待时间不够长,没有加载所有页面,提取不到信息而报错。

from selenium import webdriver
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import xlwt
import time

n = 1
word = input('请输入要搜索的关键词:')
driver = webdriver.Chrome()
wait = WebDriverWait(driver,10)

excl = xlwt.Workbook(encoding='utf-8', style_compression=0)

sheet = excl.add_sheet('b站视频:'+word, cell_overwrite_ok=True)
sheet.write(0, 0, '名称')
sheet.write(0, 1, 'up主')
sheet.write(0, 2, '播放量')
sheet.write(0, 3, '视频时长')
sheet.write(0, 4, '链接')
sheet.write(0, 5, '发布时间')

def search():
    driver.get("https://www.bilibili.com/")
    input = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'nav-search-input')))
    button = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'nav-search-btn')))

    input.send_keys(word)
    button.click()
    print('开始搜索:'+word)
    windows = driver.window_handles
    driver.switch_to.window(windows[-1])
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,
                                               '#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.video.i_wrapper.search-all-list')))
    get_source()
    print('开始下一页:')
    button_next = driver.find_element(By.CSS_SELECTOR,
                                      '#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.flex_center.mt_x50.mb_x50 > div > div > button:nth-child(11)')
    button_next.click()
    #time.sleep(2)
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.video-list.row > div:nth-child(1) > div > div.bili-video-card__wrap.__scale-wrap > div > div > a > h3')))
    get_source()
    print("完成")

def next_page():
    button_next = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,
                                      '#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.flex_center.mt_x50.mb_lg > div > div > button:nth-child(11)')))
    button_next.click()
    print("开始下一页")
    #time.sleep(5)
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,
                                               '#i_cecream > div > div:nth-child(2) > div.search-content > div > div > div.video-list.row > div:nth-child(1) > div > div.bili-video-card__wrap.__scale-wrap > div > div > a > h3')))
    get_source()
    print("完成")
    
def save_excl(soup):
    list = soup.find(class_='video-list row').find_all(class_="bili-video-card")
    for item in list:
        # print(item)
        video_name = item.find(class_='bili-video-card__info--tit').text
        video_up = item.find(class_='bili-video-card__info--author').string
        video_date = item.find(class_='bili-video-card__info--date').string
        video_play = item.find(class_='bili-video-card__stats--item').text
        video_times = item.find(class_='bili-video-card__stats__duration').string
        video_link = item.find('a')['href'].replace('//', 'https://')
        print(video_name, video_up, video_play, video_times, video_link, video_date)

        global n

        sheet.write(n, 0, video_name)
        sheet.write(n, 1, video_up)
        sheet.write(n, 2, video_play)
        sheet.write(n, 3, video_times)
        sheet.write(n, 4, video_link)
        sheet.write(n, 5, video_date)

        n = n +1
        
def get_source():
    html = driver.page_source
    soup = BeautifulSoup(html, 'lxml')
    save_excl(soup)
    
def main():
    search()
    for i in range(1,10):
        next_page()
        i = i + 1
    driver.close()
    
if __name__ == '__main__':
    main()
    excl.save('b站'+word+'视频.xls')

执行输入MV执行结果:

在文件夹也生成了excel文件表

打开,信息保存完成

同理,输入其他关键词,也可以。

以上,简单爬取搜索信息就完成了,如果要在服务器上隐藏运行,参考我上篇文章:python爬虫之selenium库

相关推荐

Python钩子函数实现事件驱动系统(created钩子函数)

钩子函数(HookFunction)是现代软件开发中一个重要的设计模式,它允许开发者在特定事件发生时自动执行预定义的代码。在Python生态系统中,钩子函数广泛应用于框架开发、插件系统、事件处理和中...

Python函数(python函数题库及答案)

定义和基本内容def函数名(传入参数):函数体return返回值注意:参数、返回值如果不需要,可以省略。函数必须先定义后使用。参数之间使用逗号进行分割,传入的时候,按照顺序传入...

Python技能:Pathlib面向对象操作路径,比os.path更现代!

在Python编程中,文件和目录的操作是日常中不可或缺的一部分。虽然,这么久以来,钢铁老豆也还是习惯性地使用os、shutil模块的函数式API,这两个模块虽然功能强大,但在某些情况下还是显得笨重,不...

使用Python实现智能物流系统优化与路径规划

阅读文章前辛苦您点下“关注”,方便讨论和分享,为了回馈您的支持,我将每日更新优质内容。在现代物流系统中,优化运输路径和提高配送效率是至关重要的。本文将介绍如何使用Python实现智能物流系统的优化与路...

Python if 语句的系统化学习路径(python里的if语句案例)

以下是针对Pythonif语句的系统化学习路径,从零基础到灵活应用分为4个阶段,包含具体练习项目和避坑指南:一、基础认知阶段(1-2天)目标:理解条件判断的逻辑本质核心语法结构if条件:...

[Python] FastAPI基础:Path路径参数用法解析与实例

查询query参数(上一篇)路径path参数(本篇)请求体body参数(下一篇)请求头header参数本篇项目目录结构:1.路径参数路径参数是URL地址的一部分,是必填的。路径参...

Python小案例55- os模块执行文件路径

在Python中,我们可以使用os模块来执行文件路径操作。os模块提供了许多函数,用于处理文件和目录路径。获取当前工作目录(CurrentWorkingDirectory,CWD):使用os....

python:os.path - 常用路径操作模块

应该是所有程序都需要用到的路径操作,不废话,直接开始以下是常用总结,当你想做路径相关时,首先应该想到的是这个模块,并知道这个模块有哪些主要功能,获取、分割、拼接、判断、获取文件属性。1、路径获取2、路...

原来如此:Python居然有6种模块路径搜索方式

点赞、收藏、加关注,下次找我不迷路当我们使用import语句导入模块时,Python是怎么找到这些模块的呢?今天我就带大家深入了解Python的6种模块路径搜索方式。一、Python模块...

每天10分钟,python进阶(25)(python进阶视频)

首先明确学习目标,今天的目标是继续python中实例开发项目--飞机大战今天任务进行面向对象版的飞机大战开发--游戏代码整编目标:完善整串代码,提供完整游戏代码历时25天,首先要看成品,坚持才有收获i...

python 打地鼠小游戏(打地鼠python程序设计说明)

给大家分享一段AI自动生成的代码(在这个游戏中,玩家需要在有限时间内打中尽可能多的出现在地图上的地鼠),由于我现在用的这个电脑没有安装sublime或pycharm等工具,所以还没有测试,有兴趣的朋友...

python线程之十:线程 threading 最终总结

小伙伴们,到今天threading模块彻底讲完。现在全面总结threading模块1、threading模块有自己的方法详细点击【threading模块的方法】threading模块:较低级...

Python信号处理实战:使用signal模块响应系统事件

信号是操作系统用来通知进程发生了某个事件的一种异步通信方式。在Python中,标准库的signal模块提供了处理这些系统信号的机制。信号通常由外部事件触发,例如用户按下Ctrl+C、子进程终止或系统资...

Python多线程:让程序 “多线作战” 的秘密武器

一、什么是多线程?在日常生活中,我们可以一边听音乐一边浏览新闻,这就是“多任务处理”。在Python编程里,多线程同样允许程序同时执行多个任务,从而提升程序的执行效率和响应速度。不过,Python...

用python写游戏之200行代码写个数字华容道

今天来分析一个益智游戏,数字华容道。当初对这个游戏颇有印象还是在最强大脑节目上面,何猷君以几十秒就完成了这个游戏。前几天写2048的时候,又想起了这个游戏,想着来研究一下。游戏玩法用尽量少的步数,尽量...

取消回复欢迎 发表评论: