You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Selenium打印Web表格中Salary列的所有值?

如何用Selenium打印Web表格中的Salary列

你的代码存在两个关键问题:

  • 你用driver.findElement()定位的是单个单元格(第一行第6列),而非整个Salary列的所有单元格,无法实现遍历打印
  • findElement()返回单个WebElement对象,不能直接用for循环遍历,会触发类型错误

下面是修正后的代码,能正确打印Salary列的所有内容:

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Table {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();

        driver.get("https://datatables.net/examples/basic_init/test.html"); 
        // 定位Salary列的所有单元格(第6列)
        List<WebElement> salaryColumn = driver.findElements(By.xpath("//*[@id=\"example\"]/tbody/tr/td[6]"));
        Thread.sleep(10000);
        
        // 遍历所有单元格并打印文本
        for (WebElement td : salaryColumn) {
            System.out.println(td.getText());
        }  

        driver.quit();  
    }
}

关键修改说明:

  • 用findElements()替换findElement(),获取Salary列的所有单元格元素列表
  • xpath调整为//*[@id="example"]/tbody/tr/td[6],匹配tbody下所有行的第6列单元格
  • 主方法声明throws InterruptedException,避免Thread.sleep()抛出未捕获异常

内容的提问来源于stack exchange,提问作者Sanjay Mardi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 17:04:57