如何编写xpath来获取标签的值

问题描述 投票:0回答:1

需要获取上述标签的桌面版和移动版的价值。 XPath 应该使用标签来获取相应的值。

java selenium-webdriver xpath
1个回答
0
投票

您正在寻找的 XPath 是

//div[@class='PZeSbe'][.//a[text()='Largest Contentful Paint (LCP)']]//span[contains(@class,'Ykn2A')]

你可以这样使用它

String url = "https://pagespeed.web.dev/";
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);

String testUrl = "https://www.google.com/";
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
driver.findElement(By.id("i4")).sendKeys(testUrl + "\n");

String[] labels = {"Largest Contentful Paint (LCP)", "Interaction to Next Paint (INP)", "Cumulative Layout Shift (CLS)", "First Contentful Paint (FCP)", "First Input Delay (FID)", "Time to First Byte (TTFB)"};

for (String label : labels) {
    String value = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='PZeSbe'][.//a[text()='"+ label +"']]//span[contains(@class,'Ykn2A')]"))).getText();
    System.out.println(label + ": " + value);
}

driver.quit();

打印

Largest Contentful Paint (LCP): 1.2 s
Interaction to Next Paint (INP): 250 ms
Cumulative Layout Shift (CLS): 0.04
First Contentful Paint (FCP): 1 s
First Input Delay (FID): 28 ms
Time to First Byte (TTFB): 0.5 s
© www.soinside.com 2019 - 2024. All rights reserved.