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

本文详细介绍了如何使用Scrapy爬虫框架从新闻网站提取结构化数据,通过解析HTML并按照日期对新闻进行分组。示例展示了如何处理响应、提取新闻标题、链接、来源等信息并存储为ScrapyItem。
摘要由CSDN通过智能技术生成

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
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值