美丽的汤 - 根据评论旁边的位置识别标签

Kim*_*Kim 4 python beautifulsoup

我正在使用美丽的汤.

有没有什么方法可以根据它在评论旁边的位置(解析树中没有包含的内容)来获取标签?

例如,假设我有......

<html>
<body>
<p>paragraph 1</p>
<p>paragraph 2</p>
<!--text-->
<p>paragraph 3</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在这个例子中,<p>paragraph 2</p>鉴于我正在搜索评论" <!--text-->" ,我如何识别?

谢谢你的帮助.

Mar*_*air 6

注释与任何其他节点一样出现在BeautifulSoup解析树中.例如,要查找带有文本的注释,some comment text然后打印出前一个<p>元素,您可以执行以下操作:

from BeautifulSoup import BeautifulSoup, Comment

soup = BeautifulSoup('''<html>
<body>
<p>paragraph 1</p>
<p>paragraph 2</p>
<!--some comment text-->
<p>paragraph 3</p>
</body>
</html>''')

def right_comment(e):
    return isinstance(e, Comment) and e == 'some comment text'

e = soup.find(text=right_comment)

print e.findPreviousSibling('p')
Run Code Online (Sandbox Code Playgroud)

...将打印出来:

<p>paragraph 2</p>
Run Code Online (Sandbox Code Playgroud)