2024-06-17 19:14:45 发布
网友
我有以下html:
<h4>Testing</h4> <h3>Test</h3> <h3>Test2</h3> <h4>Testing2</h4>
如果变量中引用了元素<h3>Test2</h3>,那么如何找到<h4>Testing</h4>?在被引用元素之前而不是之后的元素。
<h3>Test2</h3>
<h4>Testing</h4>
使用^{}:
element.previous_sibling
或者,^{}显式查找前面的第一个h4标记:
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>
使用^{} :
或者,^{} 显式查找前面的第一个
h4
标记:演示:
相关问题 更多 >
编程相关推荐