python - 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 个我应该怎么做?
解决方案
如果您想要第一个和最后一个文本,<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
推荐阅读
- windows - 为什么不能在 Mac 上玩 PC 游戏
- c# - Xamarin Forms iOS 项目上的图像崩溃表单
- python - 将一组元组值分配给python中的真/假板
- google-apps-script - UrlFetchApp.fetch() 异常:Google 表单触发器中的 DNS 错误
- python - 如何匹配来自多个数据帧的字符串并使用 AND 和 OR 选项返回索引
- flutter - Flutter Navigator 在异步函数问题中的使用
- javascript - 使用 Jest/Enzyme 进行测试时无法在 useEffect 挂钩中访问 DOM
- reactjs - 无法在屏幕上使用带有 react-hooks-forms 的 react-datepicker 显示日期
- c++ - 为什么 std::endl 的类型推导失败?
- database - Web 应用程序 - 如何动态呈现公告