【python】使用Selenium和Chrome WebDriver来获取 【腾讯云 Cloud Studio 实战训练营】中的文章信息

在这里插入图片描述

前言

本文介绍了如何使用Selenium和Chrome WebDriver来获取 【腾讯云 Cloud Studio 实战训练营】中的文章信息。在这篇文章中,我们首先导入了需要使用的依赖库,然后设置了ChromeDriver的路径,并创建了Chrome WebDriver对象。接着,我们使用WebDriver打开了指定的网页,并等待页面加载完成。随后,通过定位元素的方式找到了搜索结果列表的父元素,并提取了每个搜索结果的标题、作者、发布时间等信息。最后,我们将提取到的数据存储为JSON文件,并关闭了WebDriver。

导入依赖库

在这里插入图片描述

from selenium import webdriver
import json
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import time

这段代码导入了需要使用的依赖库,包括seleniumjson,以及一些常用模块。

设置ChromeDriver的路径

在这里插入图片描述

driver_path = ''

在这里,driver_path变量存储了ChromeDriver的路径,需要根据实际情况进行设置。

创建Chrome WebDriver对象

driver = webdriver.Chrome(driver_path)

通过webdriver.Chrome()方法创建了一个Chrome WebDriver对象,并将其赋值给变量driver

打开网页

在这里插入图片描述

url = 'https://so.csdn.net/so/search?spm=1001.2100.3001.7499&q=%E8%85%BE%E8%AE%AF%E4%BA%91%20Cloud%20Studio%20%E5%AE%9E%E6%88%98%E8%AE%AD%E7%BB%83%E8%90%A5&t=blog&u=&utm_medium=distribute.pc_search_hot_word.none-task-hot_word-alirecmd-1-%E8%85%BE%E8%AE%AF%E4%BA%91%20Cloud%20Studio%20%E5%AE%9E%E6%88%98%E8%AE%AD%E7%BB%83%E8%90%A5-null-null.172%5Ev8%5Etag_flag&depth_1-utm_source=distribute.pc_search_hot_word.none-task-hot_word-alirecmd-1-%E8%85%BE%E8%AE%AF%E4%BA%91%20Cloud%20Studio%20%E5%AE%9E%E6%88%98%E8%AE%AD%E7%BB%83%E8%90%A5-null-null.172%5Ev8%5Etag_flag'
driver.get(url)
time.sleep(5)

使用driver.get()方法打开了指定的网页。这里的URL是搜索某个关键词的CSDN博客链接。然后通过time.sleep()方法等待页面加载完成。

找到结果元素

results = driver.find_element(By.CLASS_NAME, "so-result-list").find_elements(By.CLASS_NAME, "list-item")

使用driver.find_element()方法找到了搜索结果列表的父元素,再通过find_elements()方法找到所有的搜索结果元素,并将其赋值给变量results

创建一个空列表用于存储数据

data = []

创建一个空列表data,用于存储提取出的数据。

遍历结果元素并提取数据

for result in results:
    ...

遍历结果元素列表results,对每一个结果元素进行数据提取。

提取标题、作者、发布时间等信息

    title = result.find_element(By.CLASS_NAME, "title").find_element(By.TAG_NAME, 'a').text
    author = result.find_element(By.CLASS_NAME, "item-ft").find_element(By.CLASS_NAME, 'name-text').text
    pushTime = result.find_element(By.CLASS_NAME, "item-ft").find_element(By.CLASS_NAME, 'time').text

通过find_element()方法找到标题、作者和发布时间等元素,并使用.text属性获取对应的文本内容。

判断是否为目标文章

    if "实战训练营】" in title:
        ...
    else:
        print(f'不是目标文章, 当前文章标题是:{title}')

通过判断标题中是否包含关键字"实战训练营】"来确定是否为目标文章。如果是目标文章,则进行下一步的数据提取;否则打印当前文章的标题。

提取目标文章的描述、阅读数量、点赞数量、评论数量等信息

        description = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME, "row2").text

        try:
            read = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME,"item-ft").find_element(By.CLASS_NAME, "btm-view").find_element(By.CLASS_NAME, "num").text
        except NoSuchElementException:
            read = 0

        try:
            zan = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME,
                                                                                   "item-ft").find_element(
                By.CLASS_NAME, "btm-dig").find_element(By.CLASS_NAME, "num").text
        except NoSuchElementException:
            zan = 0

        try:
            comment = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME,
                                                                                       "item-ft").find_element(
                By.CLASS_NAME, "btm-comment").find_element(By.CLASS_NAME, "num").text
        except NoSuchElementException:
            comment = 0

使用find_element()方法逐层查找目标文章的描述、阅读数量、点赞数量、评论数量等元素,并通过.text属性获取对应的文本内容。如果某个元素不存在,则将对应的变量赋值为0。

将提取的数据存储为字典格式

        item = {
            'title': title,  # 标题
            'description': description, # 描述
            'read': read,  # 阅读数量
            'zan': zan,  # 点赞数量
            'comment': comment,  # 评论数量
            'author': author, # 作者
            'pushTime': pushTime # 发布时间
        }

将提取到的标题、描述、阅读数量等信息存储为一个字典item

将字典添加到数据列表中

        data.append(item)

将提取到的字典item添加到数据列表data中。

保存数据为JSON文件

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

使用json.dump()方法将数据列表data以JSON格式保存到文件"data.json"中。

关闭WebDriver

driver.quit()

关闭Chrome WebDriver。

完整代码

from selenium import webdriver
import json
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import time

# 设置ChromeDriver的路径
driver_path = ''

# 创建Chrome WebDriver对象
driver = webdriver.Chrome(driver_path)

# 打开网页
url = 'https://so.csdn.net/so/search?spm=1001.2100.3001.7499&q=%E8%85%BE%E8%AE%AF%E4%BA%91%20Cloud%20Studio%20%E5%AE%9E%E6%88%98%E8%AE%AD%E7%BB%83%E8%90%A5&t=blog&u=&utm_medium=distribute.pc_search_hot_word.none-task-hot_word-alirecmd-1-%E8%85%BE%E8%AE%AF%E4%BA%91%20Cloud%20Studio%20%E5%AE%9E%E6%88%98%E8%AE%AD%E7%BB%83%E8%90%A5-null-null.172%5Ev8%5Etag_flag&depth_1-utm_source=distribute.pc_search_hot_word.none-task-hot_word-alirecmd-1-%E8%85%BE%E8%AE%AF%E4%BA%91%20Cloud%20Studio%20%E5%AE%9E%E6%88%98%E8%AE%AD%E7%BB%83%E8%90%A5-null-null.172%5Ev8%5Etag_flag'
driver.get(url)
time.sleep(5)

# 找到结果元素
results = driver.find_element(By.CLASS_NAME, "so-result-list").find_elements(By.CLASS_NAME, "list-item")

# 创建一个空列表用于存储数据
data = []

# 遍历结果元素并提取数据
for result in results:
    time.sleep(5)
    title = result.find_element(By.CLASS_NAME, "title").find_element(By.TAG_NAME, 'a').text
    author = result.find_element(By.CLASS_NAME, "item-ft").find_element(By.CLASS_NAME, 'name-text').text
    pushTime = result.find_element(By.CLASS_NAME, "item-ft").find_element(By.CLASS_NAME, 'time').text

    if "实战训练营】" in title:
        description = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME, "row2").text
        # readEle = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME, "item-ft").find_element(
        #     By.CLASS_NAME, "btm-view")
        # zanEle = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME, "item-ft").find_element(
        #     By.CLASS_NAME, "btm-dig")
        # print(zanEle)
        # commentEle = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME,
        #                                                                            "item-ft").find_element(
        #     By.CLASS_NAME, "btm-comment")
        try:
            read = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME,"item-ft").find_element(By.CLASS_NAME, "btm-view").find_element(By.CLASS_NAME, "num").text
            # read = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME,
            #                                                                         "item-ft").find_element(
            #     By.CLASS_NAME, "btm-view").find_element(By.CLASS_NAME, "num").text
        except NoSuchElementException:
            read = 0

        try:
            zan = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME,
                                                                                   "item-ft").find_element(
                By.CLASS_NAME, "btm-dig").find_element(By.CLASS_NAME, "num").text


        except NoSuchElementException:
            zan = 0

        try:
            comment = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME,
                                                                                       "item-ft").find_element(
                By.CLASS_NAME, "btm-comment").find_element(By.CLASS_NAME, "num").text
        except NoSuchElementException:
            comment = 0
        # read = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME, "item-ft").find_element(By.CLASS_NAME, "btm-view").find_element(By.CLASS_NAME, "num").text
        # zan = result.find_element(By.CLASS_NAME, "item-bd__cont").find_element(By.CLASS_NAME, "item-ft").find_element(By.CLASS_NAME, "btm-dig").find_element(By.CLASS_NAME, "num").text
        # comment = result.find_element(By.CLASS_NAME,"item-bd__cont").find_element(By.CLASS_NAME, "item-ft").find_element(By.CLASS_NAME, "btm-comment").find_element(By.CLASS_NAME, "num").text
        idx = result.get_attribute('i')
        # 将提取的数据存储为字典格式
        item = {
            'title': title,  # 标题
            'description': description, # 描述
            'read': read,  # 阅读数量
            'zan': zan,  # 点赞数量
            'comment': comment,  # 评论数量
            'author': author, # 作者
            'pushTime': pushTime # 发布时间
        }
        print(idx)
        # 将字典添加到数据列表中
        data.append(item)

    else:
        print(f'不是目标文章, 当前文章标题是:{title}')

# 保存数据为JSON文件

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

# 关闭WebDriver
driver.quit()


运行效果

运行的数据会保存到json 中
在这里插入图片描述

结束语

通过本文的介绍,我们学习了如何使用Selenium和Chrome WebDriver进行网页数据爬取,掌握了定位元素、提取信息和数据存储的相关技巧。这些技术对于获取网页上的数据非常有用,可以帮助我们实现自动化的数据采集和处理。希望本文对您有所帮助!如果您对网页数据爬取和数据处理有更多兴趣和需求,可以继续深入学习和探索相关内容。祝您在数据领域取得更多的成果!

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全栈若城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值