2015-10-21 40 views
0

我想從選定的容器中獲取所有src圖像url,我嘗試使用for循環但無法完成。獲取所有src圖像選擇容器

我嘗試下面的代碼,但我得到的輸出爲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

如果您只是將該網站鏈接起來,這樣會更容易。這是很多HTML處理。 – JeffC

回答

1

這是因爲你正試圖從a標籤獲取圖像而圖像是存在於img標籤

下面的Xpath

//img[@itemprop='image'] 
0使用

以上的Xpath將返回所有圖像元素

,如果你希望其他圖像的href您可以使用下面的XPath爲href

//a[@class='product_img_link' and @href[contains(.,'262')]] 

變化從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); 

希望它會幫助你:)

+0

感謝您的澄清,你能否寫我的代碼,以便我可以得到我錯誤的地方? –

+0

其實我得到的src網址,但事實是我想獲得href,我試圖使用它,但我得到重複的url因爲有兩個'a'標籤。如何解決.. –

+0

用最新的xpath和代碼更新了我的答案 –

0

我看了看現場,證實該代碼工作。

List<WebElement> images = driver.findElements(By.cssSelector("div.product_list img")); 
for (WebElement image : images) 
{ 
    System.out.println(image.getAttribute("src")); 
} 

CSS選擇正在尋找IMAGE標記,是DIV的後裔與類product_list。然後它循環遍歷List並寫出每個IMAGEsrc屬性。

+0

感謝Jeffc,它的工作.... –

+0

謝謝@Jeffc,它的工作....但不知道如何拿出這個選擇器「div.product_list img」。如果你能解釋我,很感激。 –

+0

我通常接近一個任務一樣,這是找到一個包含所有給定產品的產品信息元素的方式......我把這種現象稱爲「容器」元素。在這種情況下,這是'product_list'類的'DIV'。你想每個產品的'IMG'標籤讓你找到你的「容器」'DIV'後代'IMG'這是'「div.product_list IMG」'。這裏有一個很好的[對CSS選擇參考(http://www.w3.org/TR/selectors/#selectors)。我建議你閱讀一些教程。 CSS選擇器功能非常強大,是任何automator的好工具。 – JeffC