Selenium Java:获取指定文本tr元素data-key属性值的方法
getAttribute("data-key") Returning Null in Selenium WebDriver (Java) Hey there! Let's break down why you're getting null here and fix it right away.
The core issue is simple: you're currently locating the <td> element that holds the text "Some name", but the data-key attribute you want is on its parent <tr> element. When you call elem.getAttribute("data-key") on the <td>, it's checking for that attribute on the wrong element—so it returns null as expected.
Here are a few straightforward solutions to get the correct attribute value:
Solution 1: Directly locate the parent <tr> element
Adjust your XPath to target the <tr> that contains a child <td> with your target text. You can use either of these valid XPath expressions:
//tr[td[text()='Some name']](Finds a<tr>where any child<td>has the exact text)//td[text()='Some name']/parent::tr(Locates the<td>first, then navigates up to its parent<tr>)
Update your test code like this:
@Test public void test() throws Exception { driver.navigate().to("some url"); // Target the <tr> element directly WebElement trElem = driver.findElement(By.xpath("//tr[td[text()='Some name']]")); String val = trElem.getAttribute("data-key"); System.out.print(val); // This should now return "20" }
Solution 2: Navigate from the <td> to its parent <tr>
If you need to keep the initial <td> locator for any reason, you can fetch the parent <tr> after locating the <td>:
@Test public void test() throws Exception { driver.navigate().to("some url"); WebElement tdElem = driver.findElement(By.xpath("//*[text() = 'Some name']")); // Traverse up to the parent <tr> WebElement trElem = tdElem.findElement(By.xpath("./parent::tr")); String val = trElem.getAttribute("data-key"); System.out.print(val); }
Bonus: Handle timing issues (if needed)
If you still run into problems, it might be because the element isn't fully loaded when you try to access it. Use an explicit wait to ensure the <tr> is visible before interacting with it:
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration; @Test public void test() throws Exception { driver.navigate().to("some url"); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement trElem = wait.until( ExpectedConditions.visibilityOfElementLocated(By.xpath("//tr[td[text()='Some name']]")) ); String val = trElem.getAttribute("data-key"); System.out.print(val); }
Note on robust text matching
If the <td> might have extra whitespace around "Some name", use these XPath tweaks to make the match more reliable:
//tr[td[contains(text(), 'Some name')]](Matches any<td>that includes the text)//tr[td[normalize-space(text())='Some name']](Trims whitespace before checking for an exact match)
内容的提问来源于stack exchange,提问作者Daria

