仅在 H2 内抓取内容 - BeautifulSoup

Scrape content only inside H2 - BeautifulSoup

我有这个标记。

<h2>
  Virtual Office packages
  <span>From</span><span class="cost">.97</span>
</h2>

有时

<h2>Virtual Office packages</h2>

和这段代码。

service_header = service.select("h2")[0].string

我只想获取 Virtual Office packages 而不是价格信息。

我可以在第二种情况下得到它,但如果 HTML 像第一个一样找到,我会得到 None,有价格信息。

准确地说,如何只获得“Virtual Office 软件包”以及任何一种 HTMLs?

soup = BeautifulSoup("""
<h2>
  Virtual Office packages
  <span>From</span><span class="cost">.97</span>
</h2>""")


print(soup.find("h2").next_element.strip())
Virtual Office packages


soup = BeautifulSoup("""
<h2>Virtual Office packages</h2>
""")


print(soup.find("h2").next_element)

Virtual Office packages

soup = BeautifulSoup("""
<h2>
  Virtual Office packages
  <span>From</span><span class="cost">.97</span>
</h2>""")


print(soup.find("h2").contents[0].strip())
Virtual Office packages

soup = BeautifulSoup("""
<h2>Virtual Office packages</h2>
""")

print soup.find("h2").contents[0]
Virtual Office packages