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

如何使用Selenium WebDriver(Java)抓取表格数据并点击姓名进入详情

Hey there! Let's tackle your two Selenium WebDriver (Java) questions one by one:

问题1:如何使用Selenium WebDriver(Java)抓取表格内的数据?

Grabbing table data in Selenium is straightforward once you break down the table's structure. Here's a step-by-step approach with practical code examples:

  1. Locate the target table: First, identify the table using a reliable selector like id, XPath, or CSS selector.
  2. Iterate through rows: Fetch all rows (usually <tr> elements) — if you want to skip headers, target rows inside the <tbody> tag specifically.
  3. Extract cell content: For each row, grab all cells (<td> elements) and pull their text data.

Example Code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;
import java.util.List;

// Wait for the table to load (critical for dynamic pages)
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement table = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("your-table-id")));

// Get all rows from the table body
List<WebElement> rows = table.findElements(By.cssSelector("tbody tr"));

// Loop through each row to extract cell data
for (WebElement row : rows) {
    List<WebElement> cells = row.findElements(By.tagName("td"));
    StringBuilder rowData = new StringBuilder();
    
    for (WebElement cell : cells) {
        String cellText = cell.getText().trim();
        rowData.append(cellText).append("\t");
        // Store this data in a List, Map, or database as needed
    }
    
    System.out.println("Row data: " + rowData);
}

Key Notes:

  • Always use WebDriverWait to wait for elements to be visible/interactable — this avoids issues with dynamically loaded tables.
  • If your table uses <th> for headers, adjust your selector to exclude them if you don't need header data.
  • For complex tables (like merged cells), you’ll need more specific XPath/CSS selectors to target the correct cells.

问题2:点击表格中"first name"列的每个姓名进入详情页

Looking at your code snippet, I spot a common mistake: you’re using findElement() instead of findElements() — this only returns the first matching element, not all names. Plus, when you navigate away from the table page and return, your original WebElement references will become stale (invalid), so we need to re-locate elements each loop iteration.

Fixed & Improved Code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;
import java.util.List;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// First, get the total number of name elements to loop through
WebElement initialTable = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ember2185")));
List<WebElement> nameElements = initialTable.findElements(By.className("ember-view vertical-item"));
int totalNames = nameElements.size();

// Loop using index to avoid stale element issues
for (int i = 0; i < totalNames; i++) {
    // Re-locate the table and current name element every time we return to the page
    WebElement refreshedTable = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ember2185")));
    List<WebElement> refreshedNameElements = refreshedTable.findElements(By.className("ember-view vertical-item"));
    
    // Click the name to open the detail page
    refreshedNameElements.get(i).click();
    
    // --- Perform your deep query on the detail page here ---
    // Example: Extract customer details
    // String customerEmail = driver.findElement(By.id("customer-email")).getText();
    // System.out.println("Customer Email: " + customerEmail);
    
    // Navigate back to the table page
    driver.navigate().back();
    
    // Wait for the table to reload before the next iteration
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ember2185")));
}

Important Tips:

  • Precise Selectors: If ember-view vertical-item isn’t exclusive to the "first name" column, refine your selector. For example, use XPath to target the specific column:
    By nameSelector = By.xpath("//table[@id='ember2185']//td[contains(@class, 'first-name-column')]/a");
    
  • New Tab Handling: If clicking the name opens a new tab, use window handles to switch between tabs:
    String originalWindow = driver.getWindowHandle();
    refreshedNameElements.get(i).click();
    // Switch to new tab
    for (String windowHandle : driver.getWindowHandles()) {
        if (!windowHandle.equals(originalWindow)) {
            driver.switchTo().window(windowHandle);
            break;
        }
    }
    // Handle detail page...
    driver.close(); // Close new tab
    driver.switchTo().window(originalWindow); // Switch back
    
  • Stale Element Prevention: Re-locating elements in each loop avoids StaleElementReferenceException, which happens when the page DOM refreshes after navigation.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:17:55