查找元素的先前出现 [英] Find previous occurrence of an element

查看:40
本文介绍了查找元素的先前出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html:

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

如果我在变量中引用了元素< h3> Test2</h3> ,如何找到< h4> Testing</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.

推荐答案

使用 .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>

这篇关于查找元素的先前出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆