繁体   English   中英

使用BeautifulSoup的findAll搜索html元素的innerText以获得与搜索属性相同的结果?

[英]Using BeautifulSoup's findAll to search html element's innerText to get same result as searching attributes?

例如,如果我按元素的属性(例如id)进行搜索:

soup.findAll('span',{'id':re.compile("^score_")})

我返回匹配的整个span元素的列表(我喜欢)。

但是,如果我尝试通过html元素的innerText搜索,如下所示:

soup.findAll('a',text = re.compile("discuss|comment")) 

我只获得匹配的元素back的innerText部分,而不是像上面那样带有标签和属性的整个元素。

这可能与找不到匹配项然后让它成为父项有关吗?

谢谢。

您不会取回文字。 您将获得带有文本的NavigableString 该对象具有转到父对象的方法,等等。

from BeautifulSoup import BeautifulSoup
import re

soup = BeautifulSoup('<html><p>foo</p></html>')

r = soup.findAll('p', text=re.compile('foo'))

print r[0].parent

版画

<p>foo</p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM