2017-05-04 128 views
0

無法獲取網頁中的所有鏈接 - Selenium 無法使用下面提到的代碼從網頁獲取所有鏈接。下面 代碼:無法獲取網頁中的所有鏈接 - Selenium

package config; 



import java.util.concurrent.TimeUnit; 
import java.util.List; 

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.interactions.Actions; 
import org.openqa.selenium.remote.DesiredCapabilities; 
import org.openqa.selenium.support.ui.WebDriverWait; 
import org.testng.annotations.AfterTest; 
import org.testng.annotations.BeforeTest; 
import org.testng.annotations.Test; 

public class ActionKeywords { 
// WebDriver driver = new FirefoxDriver(); 

    WebDriver driver; 

    @BeforeTest 
    public void setup() 
    { 
     System.setProperty("webdriver.gecko.driver", "E:\\geckodriver-v0.16.1-win64\\geckodriver.exe"); 
     DesiredCapabilities dc = DesiredCapabilities.firefox(); 
     dc.setCapability("marionette", true); 
     driver = new FirefoxDriver(dc); 
     driver.manage().window().maximize(); 
    } 

    @Test 
    public void openBrowser(){ 
     driver.get("https://www.google.com/"); 
    } 



/* 
@Test 
    public void verify_Menus(){ 

     WebElement mainMenu = driver.findElement(By.xpath("//ul[@id='menu-main']/li/a")); 
     System.out.println(mainMenu.getText()); 
     WebElement subMenu = driver.findElement(By.xpath("//a[contains(text(),'Impegno Per La Natura')]")); 
     Actions action = new Actions (driver); 
     action.moveToElement(mainMenu).perform(); 
     System.out.println(subMenu.getText()); 
     action.click(subMenu).perform(); 
    } */ 

    @Test 
    public void all_Links(){ 
     try{ 
     List<WebElement> allLinks = driver.findElements(By.tagName("a")); 
     System.out.println("Count of all links: " +allLinks.size()); 

     //Loop 
     for (WebElement link : allLinks) 
      System.out.println(link.getText()); 


    }catch (Exception e){ 
     System.out.println("Element not found by tagName"); 
    } 
    } 

    @AfterTest 
    public void close_Browser(){ 
     driver.quit(); 
    } 
} 

運行後這個方案,結果顯示爲「所有鏈接的次數:0 請指教!

感謝, 的Sudhir

回答

0

您將獲得使用包含屬性的所有鏈接HREF/SRC像顯示在下面的代碼:

@Test 
    public void alllinks() 
    { 
     System.setProperty("webdriver.chrome.driver", "D:/Selenium/Drivers/chromedriver.exe"); 
     WebDriver driver = new ChromeDriver(); 
     driver.manage().window().maximize(); 

    driver.get("http://www.google.com"); 

    List<WebElement> list=driver.findElements(By.xpath("//*[@href or @src]")); 

    for(WebElement e : list){ 
     String link = e.getAttribute("href"); 
     if(null==link) 
      link=e.getAttribute("src"); 
     System.out.println(e.getTagName() + "=" + link); 
    } 
    } 

希望這個代碼將幫助你。

感謝

0

您使用的是正確的代碼,但(()以錯誤的順序all_Links執行)方法是先執行openBrowser之前。 請將優先級放在@test註釋中,因爲@test註釋按默認字母順序運行。

希望這對你有幫助!

0

如果您可以將driver.get("https://www.google.com/");OpenBrowser()更改爲SetUp()將會更好。 OpenBrowser()不應該是一個測試,它可能會干擾執行的順序。

相關問題