XPath 不定位元素

XPath doesn't locate element

我想从这个页面抓取链接。 https://www.youtube.com/results?search_query=food+recepies

WebElement w1 = driver.findElement(By.xpath("//a[@id=\"video-title\"]"));
WebElement w2 = driver.findElement(By.xpath("//*a[@id='video-title']"));
WebElement w3 = driver.findElement(By.xpath("//a[@class='yt-simple-endpoint style-scope ytd-video-renderer']"));
WebElement w4 = driver.findElement(By.xpath("//h3/a"));

String link = w1.getAttribute("href");

None 这些对我有用。

Error: Unable to locate element: //a[@id="video-title"]

这应该适用于标题。

driver.findElement(By.xpath("//a[@id='video-title']"));

但是,有27个。所以,你可能想使用

List<WebElement> plants = driver.findElements(By.xpath("//a[@id='video-title']"));

另一件事是,您可能希望等到页面上的元素可见、启用、可点击等。为此,您需要执行以下操作:

WebElement firstResult = new WebDriverWait(driver, Duration.ofSeconds(10))
     .until(ExpectedConditions.elementToBeVisible(By.xpath("//a[@id='video-title']")));