【问题标题】:how to use beautifulSoup to extract html5 elements such as <section>如何使用beautifulSoup提取<section>等html5元素
【发布时间】:2020-02-21 08:51:09
【问题描述】:

我打算从 NYT 文章中提取文章文本。但是我不知道如何通过节名等html5标签进行提取。

import urllib.request
from bs4 import BeautifulSoup

html = urllib.request.urlopen('https://www.nytimes.com/2019/10/24/opinion/chuck-schumer-electric-car.html?action=click&module=Opinion&pgtype=Homepage')
soup = BeautifulSoup(html)
data = soup.findAll(text=True)

正文包含在名为“articleBody”的部分中。我可以使用什么样的 soup.find() 语法来提取它?

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    find 方法搜索标签,它不区分 HTML5 和任何其他 (X)HTML 标签名称

    article = soup.find("section",{"name":"articleBody"})
    

    【讨论】:

    • 感谢您的回复。这只是返回一个大的 js 文件。是因为付费墙吗?我还能如何提取纯文本?
    • 可能是付费墙,或 NYT 使用 JS 从支持 API 加载动态内容。在这种情况下,您必须开始使用 selenium WebDriver
    【解决方案2】:

    您可以从脚本标签中抓取预加载的数据并使用 json 库进行解析。第一个代码块带回的内容比您想要的多一点。

    您可以通过在正文中查找段落的 id 来进一步限制,并使用它们来过滤内容,如底部块所示;然后您就可以得到您所描述的文章内容。

    import requests, re, json
    
    r = requests.get('https://www.nytimes.com/2019/10/24/opinion/chuck-schumer-electric-car.html?action=click&module=Opinion&pgtype=Homepage')
    p = re.compile(r'window\.__preloadedData = (.*})')
    data = json.loads(p.findall(r.text)[0])
    
    for k,v in data['initialState'].items():
        if k.startswith('$Article') and 'formats' in v:
            print(v['text@stripHtml'] if 'text@stripHtml' in v else v['text'])
    

    您可以在此处探索 json:https://jsoneditoronline.org/?id=f9ae1fb774af439d8e9b32247db9d853


    下面展示了如何使用额外的逻辑来限制你想要的输出:

    ids = []
    
    for k,v in data['initialState'].items():
        if k.startswith('$Article') and v['__typename'] == 'ParagraphBlock' and 'content' in v:
            ids += [v['content'][0]['id']]
    
    for k,v in data['initialState'].items():
        if k in ids:
            print(v['text'])  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多