查找以前出现的元素

时间:2014-12-28 23:16:37

标签: python html beautifulsoup html-parsing

我有以下html:

<h4>Testing</h4>
<h3>Test</h3>
<h3>Test2</h3>
<h4>Testing2</h4>

如果我在变量中引用了元素<h3>Test2</h3>,我该如何找到<h4>Testing</h4>之前引用的元素,而不是之后。

1 个答案:

答案 0 :(得分:9)

使用.previous_sibling

element.previous_sibling

或者,.find_previous_sibling()明确找到前一个h4标记:

element.find_previous_sibling('h4')

演示:

>>> from bs4 import BeautifulSoup
>>> data = """
... <h4>Testing</h4>
... <h3>Test</h3>
... <h3>Test2</h3>
... <h4>Testing2</h4>
... """
>>> soup = BeautifulSoup(data)
>>> element = soup.find('h3', text='Test')
>>> element.find_previous_sibling('h4')
<h4>Testing</h4>
相关问题