我想从所选容器中获取所有src图像网址,我尝试使用for循环但无法完成它。
我尝试了以下代码,但我的输出为Null
WebElement img=driver.findElement(By.xpath("//*[@id='center_column']/div[2]"));
List<WebElement> imgclass= img.findElements(By.xpath("//a[@itemprop='url']"));
for(int i=0;i<imgclass.size();i++){
List<WebElement> srcimg=imgclass.get(i).findElements(By.tagName("img"));
for(int j=0 ;j<imgclass.size();j++){ System.out.println("Output"+imgclass.get(j).getAttribute("href"));
}
但是无法弄清楚为什么我会得到重复的网址:
答案 0 :(得分:1)
之所以发生这种情况,是因为当a
代码中存在图片时,您试图从img
代码获取图片
在Xpath下面使用
//img[@itemprop='image']
Xpath上方将返回所有图像的元素
您可以使用以下xpath作为href
//a[@class='product_img_link' and @href[contains(.,'262')]]
如果您想要其他图像href
,请将值从262更改为261现在只需要.getAttribute("href")
来检索完整的网址。如下: -
String a = driver.findElement(By.xpath("//a[@class='product_img_link' and @href[contains(.,'262')]]")).getAttribute("href");
完整代码: -
WebDriver driver=new FirefoxDriver();
driver.get("https://www.domain.com/categories");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
String a = driver.findElement(By.xpath("//a[@class='product_img_link' and @href[contains(.,'261')]]")).getAttribute("href");
System.out.println(a);
希望它会对你有所帮助:)。
答案 1 :(得分:0)
我查看了该网站并确认此代码有效。
List<WebElement> images = driver.findElements(By.cssSelector("div.product_list img"));
for (WebElement image : images)
{
System.out.println(image.getAttribute("src"));
}
CSS Selector正在查找IMAGE
个标记,这些标记是DIV
的后代,其中包含类product_list
。然后循环遍历List
并为每个src
写出IMAGE
属性。