你好,我是新来的硒铬驱动。我正在抓取电子商务网站,在那里我从主页上抓取所有产品的详细信息,但在该页面中,产品图像是动态加载的(在5-7秒后,当产品加载)。源代码是这样的
<img alt="product1" class="image" />
5-7秒后
<img alt="product1" class="image" src="product image url" />
所以我想抓取图像src
属性值。
我试过用下面的方法
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
或
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
或
Thread.sleep(20000)
但是我失败了,有谁能帮我获取图片src
属性值吗?
发布于 2020-08-01 21:20:56
Selenium的"FluentWait“是你的朋友
final WebElement imgWithSrc = new FluentWait<>(driver)
.withTimeout(Duration.of(10_000, ChronoUnit.MILLIS))
.pollingEvery(Duration.of(250, ChronoUnit.MILLIS))
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class)
.ignoring(ScriptTimeoutException.class)
.until(d -> {
final WebElement imgElement = d.findElement(By.cssSelector("img.image"));
if (StringUtils.isNotBlank(imgElement.getAttribute("src"))) {
return imgElement;
}
return null;
});
在第二行中,您可以看到最大值。等待10s,每250ms轮询一次(第三行)
发布于 2020-08-02 04:30:34
试试这个:
WebElement image = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.of(10, ChronoUnit.SECONDS))
.until(
ExpectedConditions.presenceOfElementLocated(
By.xpath("//img[@alt='product1'][@src]")
)
);
上面的代码意味着,除非您的DOM获得xpath
中描述的元素,否则服务生将轮询您的DOM达10
秒。xpath的这个[@src]
部分意味着我们查询具有src
属性的元素,因此除非将所需的属性分配给元素,否则不会返回正结果。
https://stackoverflow.com/questions/63204479
复制相似问题