【问题标题】:BeautifulSoup parse unstructured htmlBeautifulSoup 解析非结构化 html
【发布时间】:2015-09-14 07:14:41
【问题描述】:

尝试用 BeautifulSoup 解析这个 html:

<div class="container">
  <strong>Monday</strong> Some info here...<br /> and then some <br />
  <strong>Tuesday</strong> Some info here...<br />
  <strong>Wednesday</strong> Some info here...<br />
  ...
</div>

我希望只能获取周二的数据:&lt;strong&gt;Tuesday&lt;/strong&gt; Some info here...&lt;br /&gt; 但由于没有包装器 div,我很难仅获取此数据。有什么建议?

【问题讨论】:

    标签: python beautifulsoup html-parsing


    【解决方案1】:

    这样怎么样:

    from bs4 import BeautifulSoup
    
    html = """<div class="container">
      <strong>Monday</strong> Some info here...<br /> and then some <br />
      <strong>Tuesday</strong> Some info here...<br />
      <strong>Wednesday</strong> Some info here...<br />
      ...
    </div>"""
    soup = BeautifulSoup(html)
    result = soup.find('strong', text='Tuesday').findNextSibling(text=True)
    print(result.decode('utf-8'))
    

    输出:

     Some info here...
    

    根据评论更新:

    基本上,您可以继续获取&lt;strong&gt;Tuesday&lt;/strong&gt; 的下一个同级文本,直到该文本的下一个同级元素是另一个&lt;strong&gt; 元素或none

    from bs4 import BeautifulSoup
    
    html = """<div class="container">
      <strong>Monday</strong> Some info here...<br /> and then some <br />
      <strong>Tuesday</strong> Some info here...<br /> and then some <br />
      <strong>Wednesday</strong> Some info here...<br />
      ...
    </div>"""
    soup = BeautifulSoup(html)
    result = soup.find('strong', text='Tuesday').findNextSibling(text=True)
    nextSibling = result.findNextSibling()
    while nextSibling and nextSibling.name != 'strong':
        print(result.decode('utf-8'))
        result = nextSibling.findNextSibling(text=True)
        nextSibling = result.findNextSibling()
    

    输出:

     Some info here...
     and then some 
    

    【讨论】:

    • 是的,但它只包含 html 到第一个
      标签,我需要从 到下一个 的所有内容。
    • user1121487 您最初的问题是您在第一个答案“仅获取周二的数据:周二这里有一些信息......
      ”。如果您想要“从 到下一个 的所有内容”,那么您最初应该清楚这一点。 @har07 的原始答案满足了您最初的要求。
    • 我认为从示例中的结构中可以清楚地看出,我需要从强到强的所有内容,这就是星期二的所有内容,因为您无法确定会有多少 br 等。 @serk
    猜你喜欢
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 2018-04-07
    • 1970-01-01
    相关资源
    最近更新 更多