
在web自动化测试和数据抓取中,从复杂的html结构,尤其是web表格中提取特定信息,是一项常见且关键的任务。当目标文本嵌套在<td>标签内的<span>标签中时,我们需要采用可靠的selenium定位策略来准确获取这些数据。
在深入具体策略之前,了解Selenium如何定位元素以及如何获取其文本至关重要。
1. 元素定位器 (Locators) Selenium提供了多种定位策略,通过By类使用:
2. 文本获取方法
对于本教程的场景,element.text通常是最佳选择。
如果目标<span>标签具有独特的属性(如id、class)或其在页面中的XPath/CSS路径相对稳定且唯一,我们可以直接通过定位器来获取它。
立即学习“Python免费学习笔记(深入)”;
示例HTML结构:
<td style="padding:2px 2px 2px 5px;width:25%;white-space:nowrap;text-align:left;">
<span tabindex="0">11/29/2023 04:01:10</span>
</td>Python代码示例:
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 为了演示,我们使用无头模式和模拟HTML内容
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=options)
mock_html_content = """
<!DOCTYPE html>
<html>
<head><title>Web Table Demo</title></head>
<body>
<table id="myDataTable" border="1">
<tbody>
<tr>
<td>Data 1-1</td>以上就是Selenium Python:从Web表格中高效提取Span标签的文本内容的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号