我有这个标记。
<h2>
Virtual Office packages
<span>From</span><span class="cost">$74.97</span>
</h2>
有时
<h2>Virtual Office packages</h2>
和这段代码。
service_header = service.select("h2")[0].string
我只想获取
Virtual Office packages
而不是价格信息。我可以在第二种情况下得到它,但是如果找到的HTML与第一个类似,则我得到
None
,其中包含价格信息。确切地说,如何只获得带有两种HTML的“虚拟Office软件包”?
最佳答案
soup = BeautifulSoup("""
<h2>
Virtual Office packages
<span>From</span><span class="cost">$74.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">$74.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
关于python - 仅在H2内部抓取内容-BeautifulSoup,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27786052/