【问题标题】:Python: failed to get all the text in all the <span> tags using BeautifulSoupPython:未能使用 BeautifulSoup 获取所有 <span> 标记中的所有文本
【发布时间】:2016-03-29 14:49:15
【问题描述】:

我查看了 stackoverflow,但仍然没有找到解决方案。 这是我需要处理的 html 文件:

......<span ><span class='pl'>Director </span>: <span class='attrs'><a href="/celebrity/1022571/" rel="v:directedBy">James</a></span></span><br/>
<span ><span class='pl'>Actor</span>: <span class='attrs'><a href="/celebrity/1022571/">Tom</a></span></span><br/>
<span class="pl">Countries:</span> USA <br/>
<span class="pl">Language:</span> English <br/>......

文件中有很多span 标签。 这是我的代码:

from bs4 import BeautifulSoup

record=[]
soup=BeautifulSoup(html)
spans=soup.find_all('span')
for span in spans:
    record.append(span.text)

我使用上面提到的代码,我遇到了 2 个问题。 第一个是我在结果中得到了双 DirectorActor,因为它们位于 2 个 span 标签中。第二个问题是我无法获取&lt;br&gt; 标记之前的文本。我不想使用以下代码:

soup.find("span", text="Language:").next_sibling

因为对于每个br 标签,我都需要将该代码添加到我的项目中,这很烦人。 你有一些优雅的解决方案吗?

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    如果您想写一些通用的东西,您仍然需要使用next_siblingfind_next_sibling 定位下一个兄弟标签/文本节点。

    这是处理这两种情况的代码 - 当标签和文本节点后面有一个元素时:

    soup = BeautifulSoup(html, "html.parser")
    
    for label in soup.find_all("span", class_="pl"):
        value = label.find_next_sibling("span", class_="attrs")
        value = label.next_sibling.strip() if not value else value.get_text(strip=True)
    
        label = label.get_text(strip=True).strip(":")
        print(label, value)
    

    打印:

    Director James
    Actor Tom
    Countries USA
    Language English
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      相关资源
      最近更新 更多