【问题标题】:Get text from specific blocks excluding some nested tags从特定块中获取文本,不包括一些嵌套标签
【发布时间】:2019-07-13 19:59:17
【问题描述】:

我一直在尝试制作一个 Python 脚本,它实际上从特定元素块中提取文本,但必须排除嵌套同级元素中的一些文本。

这是我要抓取的 HTML 部分:

<div class="article_body">
    <div id="articleBodyContents">
        Stack Overflow
        <br/>
        Is Love
        <br/>
        <a href="https://example_site1.com" target="_blank">Ad</a>
        <br/>
        <a href="https://example_site2.com" target="_blank">Ad2</a>
    </div>
</div>

到目前为止,我已经取得了进展:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")
divs = soup.findAll('div', {'id':'articleBodyContents'})
for ops in divs:
    print(ops.text.replace('\n', '').strip())

但是打印出来的是:

Stack Overflow
Is love
Ad
Ad2

我想要的只是:

Stack Overflow
Is love

【问题讨论】:

    标签: python html web-scraping beautifulsoup html-parsing


    【解决方案1】:

    你快到了。你需要NavigableString 的帮助来实现这一点。只需捕获前一个父级,并对其进行迭代,检查字符串是否为NavigableString 的实例。这是您的代码:

    from bs4 import BeautifulSoup, NavigableString
    
    html = """
    <div class="article_body">
        <div id="articleBodyContents">
            Stack Overflow
            <br/>
            Is love
            <br/>
            <a href="https://example_site1.com" target="_blank">Ad</a>
            <br/>
            <a href="https://example_site2.com" target="_blank">Ad2</a>
        </div>
    </div>
    """
    
    soup = BeautifulSoup(html, "html.parser")
    divs = soup.find('div', {'class':'article_body'})
    ops = [element for element in divs.div if isinstance(element, NavigableString)]
    for op in ops:
        print(op.strip().replace('\n', ''))
    

    输出:

    Stack Overflow
    Is love
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-21
      • 2017-02-07
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多