2016-04-22 159 views
0
<div class="info"> 
     <h3> Height: 
      <span>1.1</span> 
     </h3> 
</div> 

<div class="info"> 
     <h3> Number: 
      <span>111111111</span> 
     </h3> 
</div> 

这是网站的一部分。最终,我想提取111111111.我知道我可以做 soup.find_all("div", { "class" : "info" }) 以获得两个div的列表;然而,我宁愿不必执行循环来检查它是否包含文本“数字”。Python BeautifulSoup查找包含文本的元素

是否有一种更优雅的方式来提取“1111111”,使它确实soup.find_all("div", { "class" : "info" }),但也使它必须在其中必须包含“数字”?

我也试过numberSoup = soup.find('h3', text='Number') 但它返回None

回答

1

使用XPath contains

root.xpath('//div/h3[contains(text(), "Number")]/span/text()') 
+0

谢谢!我得到它的工作。 – lclankyo

1

你可以写自己的过滤功能,让它的功能find_all的说法。

from bs4 import BeautifulSoup 

def number_span(tag): 
    return tag.name=='span' and 'Number:' in tag.parent.contents[0] 

soup = BeautifulSoup(html, 'html.parser') 
tags = soup.find_all(number_span) 

顺便说一句,你不能与text PARAM读取标签的理由是:文本PARAM帮助我们找到标签,其.string价值等于它的价值。如果一个标签包含不止一个东西,那么不清楚.string应该引用什么。所以.string被定义为None。您可以参考beautiful soup doc

相关问题