【问题标题】:How to find parent tags of an element with BeautifulSoup?如何使用 BeautifulSoup 查找元素的父标签?
【发布时间】:2018-12-08 23:43:06
【问题描述】:

我想知道是否有可能,使用漂亮的汤,几行 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 来排几行吗?

【问题讨论】:

  • 如果正确解决了您的问题,请将答案标记为已接受 :)

标签: python python-3.x beautifulsoup


【解决方案1】:

使用BeautifulSoupfind_parent /find_parents方法。

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

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

>> '12590559'

【讨论】:

  • 但是我想得到那个块的 id 因为它来自于 cracker.crc 而不是其他块因为它们是相同的但名称不同,无论如何感谢您的帮助:)
  • 就像在页面中一样,我有更多这样的代码,我想得到那块因为他有cracker.crc
  • 您的 html 块只有一个 id 标签,并且带有 td。其他区块没有id标签。
  • 那不是完整的 html 那只是一个块,我想通过文本 (Cracker.crc) 找到 thaht 块
  • 终于找到答案了,我把 find(text="Cracker") 然后 findparent 像你一样,它的工作原理!
猜你喜欢
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2017-05-04
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
  • 1970-01-01
相关资源
最近更新 更多