美丽的硒汤,如何获得第二篇文章



HTML代码

<td style="white-space: nowrap; text-align: center;">
<div style="text-align:center; table-layout: fixed; font-size: 0;">
<div style="text-align:center; vertical-align: text-top; width:16px; height:16px; display:inline-block; font-size: 12px;">10</div>
<div style="text-align:center; vertical-align: text-top; width:16px; height:16px; display:inline-block; font-size: 12px;">9/div>
<div style="text-align:center; vertical-align: text-top; width:16px; height:16px; display:inline-block; font-size: 12px;">7</div>
<div style="text-align:center; vertical-align: text-top; width:16px; height:16px; display:inline-block; font-size: 12px;">2</div>
</div>
</td>

我的代码
td_list = perform.tbody.find_all("td")
section1 = td_list[9].text.strip() # .strip skip my first element space like nn 10

输出我的结果:10 nn 9 nn7 nn2

上面的html代码中有四个文本。我想从文本中获取每个元素。我只想得到10元;我的代码只有2个我该怎么办?

如果您想要<td>的第一个和最后一个文本,您可以分别使用列表索引[0][-1]。例如:

from bs4 import BeautifulSoup
html_doc = """
<td style="white-space: nowrap; text-align: center;">
<div style="text-align:center; table-layout: fixed; font-size: 0;">
<div style="text-align:center; vertical-align: text-top; width:16px; height:16px; display:inline-block; font-size: 12px;">10</div>
<div style="text-align:center; vertical-align: text-top; width:16px; height:16px; display:inline-block; font-size: 12px;">9</div>
<div style="text-align:center; vertical-align: text-top; width:16px; height:16px; display:inline-block; font-size: 12px;">7</div>
<div style="text-align:center; vertical-align: text-top; width:16px; height:16px; display:inline-block; font-size: 12px;">2</div>
</div>
</td>
"""
soup = BeautifulSoup(html_doc, "html.parser")
td = soup.select_one("td")
text = td.get_text(strip=True, separator="n").split("n")
print(text[0])
print(text[-1])

打印:

10
2

最新更新