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

Mat*_*ira 5 python beautifulsoup python-3.x

我想知道我是否可以使用漂亮的汤,将 html 行排成几行:

<tr id="12590559" class="">
<td>
<span class="he16-1 tip-top" title="Cracker"></span>
</td>
<td>
cracker.crc
</td>
Run Code Online (Sandbox Code Playgroud)

在那个例子中,我想提取 id 但使用标题信息:

soup = BeautifulSoup(lista.content, "lxml")
id = soup.find(attrs={"title": "Cracker"})
Run Code Online (Sandbox Code Playgroud)

我可以得到

soup = BeautifulSoup(lista.content, "lxml")
id = soup.find(attrs={"title": "Cracker"})
Run Code Online (Sandbox Code Playgroud)

但我也想得到id. 我可以用BeautifulSoup来排列几条线吗?

Pra*_*eek 7

使用BeautifulSoupfind_parent/find_parents方法。

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

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

>> '12590559'
Run Code Online (Sandbox Code Playgroud)