gpt4 book ai didi

java - 根据其内容访问基于 td 元素的表中的行

转载 作者:行者123 更新时间:2023-12-02 11:45:22 26 4
gpt4 key购买 nike

我正在编写 selenium 代码来检查与特定日期匹配的 td 元素的内容。

这是我的代码:

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C://chromedriver.exe");
WebDriver driver = new ChromeDriver();
String baseUrl = "http://espn.go.com/nba";
String endPoint = "/team/schedule/_/name/chi/year/2015/chicago-bulls";

// launch browser and direct it to the Base URL
driver.get(baseUrl + endPoint);

WebElement table_element = driver.findElement(By.cssSelector(".mod-container.mod-table.mod-no-header-footer"));
List<WebElement> tr_collection = table_element.findElements(By.xpath("div/table/tbody/tr"));
for (WebElement trElement : tr_collection) {
List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
if (td_collection.get(0).getText().equals("Wed, Oct 29")) {
WebElement tdElement = td_collection.get(2);
System.out.println(tdElement.getText().split("\\n")[1]);
break;
}
}
// close browser
driver.close();
}

在这里,我获取 table 的所有行,然后检查第一列是否具有值“Wed, Oct 29”,如果匹配,则获取第三列值。

有没有办法直接查找值与“Wed, Oct 29”匹配的 td 元素?或者简化的逻辑?

最佳答案

要获取第三个元素,我想是结果列,您可以使用此 Xpath:

.//td[contains(text(),'Wed, Oct 29')]/following-sibling::td[2]

enter image description here

条件是td中的文本,用于获取他的兄弟,在本例中是第二个兄弟或第三列。

通过此 Xpaht,您可以获得 WebElement,之后您可以使用 getText 函数。该函数应该返回节点文本和所有子文本。

关于java - 根据其内容访问基于 td 元素的表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48249330/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com