按标签内容搜索BeautifulSoup

时间:2011-08-29 14:50:28

标签: python html beautifulsoup

我想通过它的文本内容搜索特定标签。例如:

<a href="http://goinghere.com">Lets go somewhere</a>

我想通过搜索文本'让我们去某个地方'来找到上述内容。 我目前正在使用re。可以在BeautifulSoup中完成,还是在这种情况下使用re更好?

1 个答案:

答案 0 :(得分:1)

s = BeautifulSoup(...)
s.find(text='Lets go somewhere')

您也可以使用正则表达式。

Using BeautifulSoup to find a HTML tag that contains certain text

编辑:如果在命令行中使用它,则find方法会打印一个字符串,这实际上只是它返回的对象的表示形式;您可以访问其上的parent属性以访问其BeautifulSoup标记对象。