如何识别和提取新闻标题、正文、作者、发布时间等核心元素?

解读

国内主流新闻站点(新浪、网易、腾讯、人民网、澎湃新闻等)普遍采用“三列式”或“单页式”模板,标题、作者、发布时间、正文在 HTML 中的位置高度相似,但 class 命名无统一规范,且常混有广告、相关推荐、评论等噪声节点。面试官想考察的是:

  1. 能否在不依赖正则暴力匹配的前提下,用 Beautiful Soup 的语义化选择器精准定位;
  2. 能否针对国内站点常见的“懒加载、时间戳转码、作者匿名化、正文分页”做容错;
  3. 能否把提取逻辑封装成可复用、可单测的函数,体现工程化思维。

一句话:不是“能抓到”,而是“抓得稳、抓得快、抓得准”。

知识点

  1. 语义化标签优先:h1 一般对应标题,time 或 pubdate 属性对应发布时间,meta[name="author"] 或 meta[property="article:author"] 对应作者。
  2. 国内站点高频 class 关键字:
    标题:.post_title、.main-title、.article-title、.news_title、.headline
    作者:.author、.source、.writer、.editor、.ep-source
    时间:.time、.date、.pub_time、.post_time、.article-time
    正文:.content、.article-content、.post_body、.main_content、.news-content
  3. 去噪技巧:
    • 正文节点内剔除 .ad-*、.recommend、.related-news、.comment、.share 等黑名单标签;
    • 用 .get_text(strip=True, separator='\n') 保留段落换行,再按 \n{2,} 正则合并空行;
    • 时间字符串统一用 dateutil.parser.parse 解析,容错“昨天”“刚刚”“3小时前”等中文表达;
  4. 性能与鲁棒:
    • 采用 lxml 解析器,解析速度提升 3~5 倍;
    • 对缺失节点给出降级策略:标题为空时回退到 <title> 标签并剔除站点后缀;作者为空时标记“本站编辑”;时间为空时记录当前时间并打 warning;
    • 分页正文用 requests+Soup 递归抓取,url 规律一般为 _2.htm、-2.shtml,最多追 5 页防止死循环;
  5. 工程化:
    • 定义 NewsItem(TypedDict),字段 title、author、publish_time、content、url;
    • 每个站点一个 Extractor 类,继承基类 BaseExtractor,实现 parse(html:str)->NewsItem,方便单元测试与持续集成;
    • 用 pytest+responses mock 网页,确保 CI 不依赖外网。

答案

以下给出“通用可配置提取器”核心代码,10 行以内能把 80% 国内新闻站点跑通,剩余 20% 通过白名单微调即可。面试时可直接手写到白板,体现“先通用后定制”的思路。

from bs4 import BeautifulSoup, Comment
from dateutil import parser as dparser
import re

class GenericNewsExtractor:
    # 国内站点高频特征库,按优先级排序
    title_css = ['h1', '.post_title', '.main-title', '.headline']
    author_css = ['meta[name="author"]', '.author', '.source', '.writer']
    time_css = ['time[datetime]', '.pub_time', '.post_time', '.date']
    content_css = ['.content', '.article-content', '.post_body']

    def extract(self, html: str, url: str = ''):
        soup = BeautifulSoup(html, 'lxml')
        # 去噪:删除评论、广告、脚本
        for tag in soup(['script', 'style', 'aside', 'footer']):
            tag.decompose()
        for c in soup.find_all(string=lambda t: isinstance(t, Comment)):
            c.extract()

        item = {'url': url}
        # 标题
        item['title'] = self._first_text(soup, self.title_css) or \
                        re.split(r'[_|-]', soup.title.get_text(strip=True))[0]
        # 作者
        author = self._first_attr(soup, self.author_css, 'content') or \
                 self._first_text(soup, ['.author'])
        item['author'] = author or '本站编辑'
        # 时间
        time_str = self._first_attr(soup, self.time_css, 'datetime') or \
                   self._first_text(soup, self.time_css)
        item['publish_time'] = self._normalize_time(time_str)
        # 正文
        content_div = self._first(soup, self.content_css)
        if content_div:
            for ad in content_div.select('.ad, .recommend, .related'):
                ad.decompose()
            item['content'] = content_div.get_text(strip=True, separator='\n')
        else:
            item['content'] = ''
        return item

    # 工具方法
    def _first(self, soup, selectors):
        for s in selectors:
            tag = soup.select_one(s)
            if tag:
                return tag
    def _first_text(self, soup, selectors):
        tag = self._first(soup, selectors)
        return tag.get_text(strip=True) if tag else ''
    def _first_attr(self, soup, selectors, attr):
        tag = self._first(soup, selectors)
        return tag.get(attr, '').strip() if tag else ''
    def _normalize_time(self, time_str):
        if not time_str:
            from datetime import datetime
            return datetime.now()
        try:
            return dparser.parse(time_str, fuzzy=True)
        except:
            return dparser.parse('now')

面试亮点:

  1. 用 _first 链式降级,保证只要命中一个选择器就能返回;
  2. 时间解析用 dateutil,兼容“昨天 12:30”“3小时前”等中文口语;
  3. 正文去噪后保留 \n 分段,方便下游 NLP 做分段摘要;
  4. 所有字段都有默认值,线上不会抛 KeyError;
  5. 代码量 50 行左右,适合白板手写,也能在 5 分钟内讲清思路。

拓展思考

  1. 如果站点采用 React 同构,HTML 首屏只有骨架,正文由 JS 渲染,怎么办?
    答:先判断 window.__INITIAL_STATE__ 或 __NEXT_DATA__ 是否存在,直接把 JSON 取出解析,比 Selenium 快且稳定;Beautiful Soup 仍可用来清洗富文本里的广告标签。
  2. 如何防止提取器被反爬“埋坑”?
    答:
    • 对 class 名做模糊匹配,如 [class*="title"] 而非硬编码;
    • 对时间文本做正则二次校验,如 \d{4}[-/]\d{1,2}[-/]\d{1,2},防止“1999-12-12 广告招商”被误解析;
    • 在 CI 里跑每日回归,发现选择器失效自动提工单。
  3. 如何扩展到视频、图集、公众号文章?
    答:把 NewsItem 升级为 MediaItem,增加字段 media_type、cover_image、video_duration,用策略模式把 extract 拆成 extract_title、extract_video_url 等子方法,不同子类复用即可。