Scrapy爬虫在新闻数据提取中的应用

news/2024/7/5 19:18:42 标签: scrapy, 爬虫

Scrapy是一个强大的爬虫框架,广泛用于从网站上提取结构化数据。下面这段代码是Scrapy爬虫的一个例子,用于从新闻网站上提取和分组新闻数据。

使用场景

在新闻分析和内容聚合的场景中,收集和组织新闻数据是常见需求。例如,如果我们需要为用户提供按日期分类的新闻更新,或者我们想分析特定时间段内的新闻趋势,这段代码就非常适合。

页面截图

在这里插入图片描述

结构截图

在这里插入图片描述

代码注释解释
# Scrapy爬虫的parse方法,用于处理响应并提取信息
def parse(self, resp, **kwargs):
    grouped_news_items = []  # 存储所有分组的新闻条目

    children = resp.xpath('//div[@class="news-list"]/*')  # 获取新闻列表中的所有子元素
    current_group = []  # 当前日期下的新闻条目集合
    current_date = None  # 当前新闻条目的日期

    # 遍历新闻列表中的每个子元素
    for child in children:
        # 如果子元素是日期标签,更新current_date并将之前的新闻组添加到grouped_news_items
        if 'news-date' in child.xpath('@class').get(''):
            if current_group:
                grouped_news_items.append((current_date, current_group))
                current_group = []
            current_date = child.xpath('normalize-space(text())').get()
        # 如果子元素是新闻条目,提取相关信息并添加到current_group
        elif 'news-item' in child.xpath('@class').get(''):
            news_info = {
                'title': child.xpath('./div/h2/a/text()').extract_first(),  # 新闻标题
                'link': child.xpath('./div/h2/a/@href').extract_first(),    # 新闻链接
                'source_name': child.xpath('./div/p/span/text()').extract()[1].strip(),  # 来源名称
                'source_img': child.xpath('./div/p/span/img/@data-src').extract_first()  # 来源图标
            }
            current_group.append(news_info)

    # 将最后一个日期的新闻条目集合添加到grouped_news_items
    if current_group:
        grouped_news_items.append((current_date, current_group))

    # 生成Scrapy Item,并通过yield返回
    for date, items in grouped_news_items:
        for item in items:
            an = AiNewsItem()  # Scrapy Item对象,用于存储新闻信息
            an['time_str'] = date
            an['title'] = item['title']
            an['source_name'] = item['source_name']
            an['source_img'] = item['source_img']
            an['link'] = item['link']
            yield an

http://www.niftyadmin.cn/n/5344272.html

相关文章

数据目录驱动测试——深入探讨Pytest插件 pytest-datadir

在软件测试中,有效管理测试数据对于编写全面的测试用例至关重要。Pytest插件 pytest-datadir 提供了一种优雅的解决方案,使得数据目录驱动测试变得更加简单而灵活。本文将深入介绍 pytest-datadir 插件的基本用法和实际案例,助你更好地组织和利用测试数据。 什么是pytest-da…

HNU-数据挖掘-实验4-链接预测

数据挖掘课程实验实验4 链接预测 计科210X 甘晴void 202108010XXX 文章目录 数据挖掘课程实验<br>实验4 链接预测实验背景实验要求数据集解析实验建模实验探索过程失败的探索——DGL库<0> DGL库简介<1> 读取基因并构建图<2> 构建GNN模型<3> 训…

打 jar 包运行 在windows 平台控制台和日志 乱码解决

--拒絕鷄巴囉嗦&#xff0c;直接解決問題 我们在Windows下运行jar包时&#xff0c;常常会出现乱码&#xff0c;主要分为dos窗口输出的日志中出现乱码和程序返回数据出现乱码。 dos窗口输出的日志中出现乱码 执行如下命令&#xff0c;将控制台输出编码改为UTF8&#xff1a; ch…

【前端基础--1】

为后面爬虫打基础 使用Visual Studio Code&#xff08;VS Code&#xff09; https://code.visualstudio.com/#alt-downloads 网页基础 创建一个html网页 新建一个文件 文件名后缀.html 书写网页模板 html:5 回车键&#xff08;或者Tab键&#xff09;英文感叹号! 回…

前端语音识别(webkitSpeechRecognition)

前端语音识别(webkitSpeechRecognition)-CSDN博客 Excerpt 文章浏览阅读1.8k次,点赞4次,收藏4次。浏览器实现语音转文字_webkitspeechrecognition webkitSpeechRecognition(语音识别) <span class="token comment">// 创建一个webkitSpeechRecognition实…

模型选择实战

我们现在可以通过多项式拟合来探索这些概念。 import math import numpy as np import torch from torch import nn from d2l import torch as d2l生成数据集 给定x&#xff0c;我们将使用以下三阶多项式来生成训练和测试数据的标签&#xff1a; max_degree 20 # 多项式的最…

Kotlin for loop: in、 until、 step、 downTo

Kotlin for loop: in、 until、 step、 downTo fun loop1() {for (i in 0..5) {print("$i ")}println("\n1-end\n") }fun loop2() {for (i in 0 until 5) {print("$i ")}println("\n2-end\n") }fun loop3() {for (i in 0 until (5)) {…

深度学习在物理层信号处理中的应用研究

随着移动流量呈现的爆发式增长、高可靠性和低时延的通信场景给当前网络带来了更大的复杂性和计算挑战。据IBM报道&#xff0c;移动数据量到2020年将超过40万亿Gbits&#xff0c;比2009年增加44倍&#xff0c;连接总设备量将达到500亿。为了满足这一需求&#xff0c;需要新的通信…