V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
itskingname
V2EX  ›  分享创造

新闻网页通用抽取器 GNE v0.04 版更新,支持提取正文图片与源代码

  •  
  •   itskingname · 2019-11-26 12:19:10 +08:00 · 2951 次点击
    这是一个创建于 1585 天前的主题,其中的信息可能已经有所发展或是发生改变。

    GeneralNewsExtractor以下简称GNE是一个新闻网页通用抽取器,能够在不指定任何抽取规则的情况下,把新闻网站的正文提取出来。

    我们来看一下它的基本使用方法。

    安装 GNE

    使用 pip 安装:

    pip install --upgrade git+https://github.com/kingname/GeneralNewsExtractor.git
    

    当然你也可以使用pipenv安装:

    pipenv install git+https://github.com/kingname/GeneralNewsExtractor.git#egg=gne
    

    获取新闻网页源代码

    GNE 现在不会,将来也不会提供网页请求的功能,所以你需要自行想办法获取经过渲染以后的网页源代码。你可以使用Selenium或者Pyppeteer或者直接从浏览器上复制。

    这里演示如何直接从浏览器中复制网页的源代码:

    1. 在 Chrome 浏览器中打开对应页面,然后开启开发者工具,如下图所示:

    1. 在 Elements 标签页定位到标签,并右键,选择 Copy-Copy OuterHTML,如下图所示

    1. 把源代码保存为 1.html

    提取正文信息

    编写如下代码:

    from gne import GeneralNewsExtractor
    
    with open('1.html') as f:
        html = f.read()
    
    extractor = GeneralNewsExtractor()
    result = extractor.extract(html)
    print(result)
    

    运行效果如下图所示:

    这次更新了什么

    在最新更新的 v0.04 版本中,开放了正文图片提取功能,与返回正文源代码功能。其中返回图片 URL 的功能在上面已经演示了,结果中的images字段就是正文中的图片。

    那么怎么返回正文源代码呢?只需要增加一个参数with_body_html=True即可:

    from gne import GeneralNewsExtractor
    
    with open('1.html') as f:
        html = f.read()
    
    extractor = GeneralNewsExtractor()
    result = extractor.extract(html, with_body_html=True)
    print(result)
    

    运行效果如下图所示:

    返回结果中的body_html就是正文的 html 源代码。

    关于 GNE 的深入使用,可以访问 GNE 的 Github: https://github.com/kingname/GeneralNewsExtractor

    1 条回复    2019-11-29 09:29:33 +08:00
    fedkwan
        1
    fedkwan  
       2019-11-29 09:29:33 +08:00
    这个我以前研究过,网页正文提取的方法。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5734 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 06:24 · PVG 14:24 · LAX 23:24 · JFK 02:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.