【问题标题】:How do you use BeautifulSoup to select a tag depending on its children and siblings?您如何使用 BeautifulSoup 根据其子级和兄弟级选择标签?
【发布时间】:2016-12-04 16:47:55
【问题描述】:

我正在尝试从 2012 年奥巴马-罗姆尼总统辩论中提取引语。问题是the site 组织得不好。所以结构看起来是这样的:

<span class="displaytext">
    <p>
        <i>OBAMA</i>Obama's first quotes
    </p>
    <p>More quotes from Obama</p>
    <p>Some more Obama quotes</p>

    <p>
        <i>Moderator</i>Moderator's quotes
    </p>
    <p>Some more quotes</p>

    <p>
        <i>ROMNEY</i>Romney's quotes
    </p>
    <p>More quotes from Romney</p>
    <p>Some more Romney quotes</p>
</span>

有没有办法选择一个&lt;p&gt;,它的第一个孩子是i,它的文本是OBAMA,并且都是p兄弟姐妹,直到你点击下一个p,它的第一个孩子是@987654328 @那个没有文字Obama??

这是我到目前为止尝试过的,但它只是抓住了第一个 p 忽略了兄弟姐妹

input = '''<span class="displaytext">
        <p>
            <i>OBAMA</i>Obama's first quotes
        </p>
        <p>More quotes from Obama</p>
        <p>Some more Obama quotes</p>

       <p>
           <i>Moderator</i>Moderator's quotes
       </p>
       <p>Some more quotes</p>

       <p>
           <i>ROMNEY</i>Romney's quotes
       </p>
       <p>More quotes from Romney</p>
       <p>Some more Romney quotes</p>
       </span>'''

soup = BeautifulSoup(input)
debate_text = soup.find("span", { "class" : "displaytext" })
president_quotes = debate_text.find_all("i", text="OBAMA")

for i in president_quotes:
    siblings = i.next_siblings
    for sibling in siblings:
        print(sibling)

仅打印Obama's first quotes

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup


    【解决方案1】:

    我认为一种类似finite state machine 的解决方案可以在这里工作。像这样:

    soup = BeautifulSoup(input, 'lxml')
    debate_text = soup.find("span", { "class" : "displaytext" })
    obama_is_on = False
    obama_tags = []
    for p in debate_text("p"):
        if p.i and 'OBAMA' in p.i:
            # assuming <i> is used only to indicate speaker
            obama_is_on = True
        if p.i and 'OBAMA' not in p.i:
            obama_is_on = False
            continue
        if obama_is_on:
            obama_tags.append(p)
    print(obama_tags)
    
    [<p>
    <i>OBAMA</i>Obama's first quotes
            </p>, <p>More quotes from Obama</p>, <p>Some more Obama quotes</p>]
    

    【讨论】:

      【解决方案2】:

      奥巴马的其他引用是p 的兄弟姐妹,而不是i,因此您需要找到i 的父母的兄弟姐妹。当您遍历这些兄弟姐妹时,您可以在其中一个有i 时停止。像这样的:

      for i in president_quotes:
          print(i.next_sibling)
          siblings = i.parent.find_next_siblings('p')
          for sibling in siblings:
              if sibling.find("i"):
                  break
              print(sibling.string)
      

      哪个打印:

      Obama's first quotes
      
      More quotes from Obama
      Some more Obama quotes
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-05
        • 2015-04-03
        • 2021-04-21
        相关资源
        最近更新 更多