Beautiful Soup - 根据评论旁边的位置识别标签

4 投票
1 回答
2618 浏览
提问于 2025-04-16 13:17

我正在使用Beautiful Soup这个工具。

有没有办法根据一个注释的位置来找到一个标签(这个注释不在解析树中)呢?

举个例子,假设我有...

<html>
<body>
<p>paragraph 1</p>
<p>paragraph 2</p>
<!--text-->
<p>paragraph 3</p>
</body>
</html>

在这个例子中,我该如何找到<p>段落 2</p>,因为我在寻找注释"<!--文本-->"呢?

谢谢大家的帮助。

1 个回答

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')

... 这样做会打印出:

<p>paragraph 2</p>

撰写回答