首页 > 解决方案 > Beautifulsoup with selenium,如何获得第二个文本

问题描述

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 \n\n 10

我的结果:10 \n\n 9 \n\n7 \n\n2

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

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


如果您想要第一个和最后一个文本,<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

推荐阅读