python - 如何使用 BeautifulSoup 查找元素的父标签?

标签 python python-3.x beautifulsoup

我想知道我是否有可能使用漂亮的汤获得几行 html 行:

<tr id="12590559" class="">
<td>
<span class="he16-1 tip-top" title="Cracker"></span>
</td>
<td>
cracker.crc
</td>

在该示例中,我想提取 id,但使用标题信息:

soup = BeautifulSoup(lista.content, "lxml")
id = soup.find(attrs={"title": "Cracker"})

我可以得到

<span class="he16-1 tip-top" title="Cracker"></span>

但我还想获得 id。我可以使用 BeautifulSoup 来排列几行吗?

最佳答案

使用 BeautifulSoup find_parent/find_parents 方法。

传递 tr 作为父搜索项,['id'] 将打印 id 值

id.find_parent('tr')['id']

>> '12590559'

关于python - 如何使用 BeautifulSoup 查找元素的父标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107486/

相关文章:

python - 如何使 BeautifulSoup 'replace_with' 属性与 'unicode' 对象一起使用?

python - 如何在 Beautifulsoup 4 中检索包含特定文本的 href?

php - 如何从 PHP 调用 Python 脚本?

python - 如何指定 Python 包的外部系统依赖项?

python - 如何搜索并用封闭的字符替换文本文件?

python - 尝试播种 YAML 数据时出现 "value must be an integer"

python - 输出的 img alt 值不正确(Python3、Beautiful Soup 4)

python - 如何让 Python 函数休眠一段时间,而游戏的其余部分继续进行?

python - 在 Python 中以编程方式启动 HiveThriftServer

python - 如何检查输入是否是Python中的自然数?