Find previous occurrence of an element

我是研究僧i 提交于 2020-12-05 07:05:45

问题


I have the following html:

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

If I have the element <h3>Test2</h3> referenced in a variable, how can I find <h4>Testing</h4>? The one before the referenced element, not after.


回答1:


Use .previous_sibling:

element.previous_sibling

Or, .find_previous_sibling() to explicitly find the first preceding h4 tag:

element.find_previous_sibling('h4')

Demo:

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


来源:https://stackoverflow.com/questions/27681602/find-previous-occurrence-of-an-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!