[英]Try get multiple links from webpage in Selenium using Java and PhantomJS
[英]Unable to get all links from the webpage - 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
您將使用包含屬性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);
}
}
希望這段代碼對您有所幫助。
謝謝
您使用的是正確的代碼,但是以錯誤的順序執行all_Links()方法是在openBrowser()之前執行的。 請在您的@test批注中放置優先級,因為@test批注默認情況下按字母順序運行。
希望這對您有幫助!!!
如果可以更改driver.get("https://www.google.com/");
會更好driver.get("https://www.google.com/");
從OpenBrowser()
到SetUp()
。 OpenBrowser()
不應被視為測試,它可能會干擾執行順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.