2017-05-04 130 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()不应该是一个测试,它可能会干扰执行的顺序。

相关问题