Unable to get all links from the webpage - Selenium
Unable to get all links from the webpage by using below mentioned code.
Code below:
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();
}
}
After run this program, result displayed as 'Count of all links: 0'
Please advise!
Thanks,
Sudhir
You will get all links using containing the attributes href / src like shown in following code:
#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);
}
}
Hope this code will help you.
Thanks
You are using the correct code But executing in wrong order all_Links() method is executing first before openBrowser().
Please put the priority in your #test annotation because #test annotation run by default alphabetical order.
Hope this will helpful to you!!!
It would be better if you can change driver.get("https://www.google.com/"); from OpenBrowser() to SetUp(). OpenBrowser() is not supposed to be a test and it can be interfering with the order of execution.
Related
I have 100+ button in the page and I have to click on each button and to verify the link and page which opens after clicking.
so how to click without writing xpath for all 100+ button, i just need to click them and for each button different page will open.
Pls help me to proceed my selenium test
After you click the first button a new DOM is loaded, so click on the second (and third ...) will end with StaleElementReferenceException. You need to get all the href values first and then try them one by one. Just tried on web bbc.com with this code:
package navi;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
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.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Himanshu {
public static WebDriver driver;
#BeforeClass
public static void setUpClass() {
FirefoxOptions options = new FirefoxOptions();
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile selenium_profile = allProfiles.getProfile("selenium_profile");
options.setProfile(selenium_profile);
options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
System.setProperty("webdriver.gecko.driver", "C:\\Users\\pburgr\\Desktop\\geckodriver-v0.20.0-win64\\geckodriver.exe");
driver = new FirefoxDriver(options);
driver.manage().window().maximize();
}
#Before public void setUp() {} #After public void tearDown() {}
#AfterClass public static void tearDownClass() {driver.quit();}
#Test
public void lots_of_buttons() throws InterruptedException {
driver.get("http://www.bbc.com/");
// wait to page is fully loaded
wait_sec(driver, 5).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"orb-header\"]/div[1]/div[1]/a/img")));
// get all the desired webelements
List<WebElement> header_links = driver.findElements(By.xpath("//a[contains(#href,'x')]"));
// create new arraylist
ArrayList<String> hrefs = new ArrayList<String>();
// collect all the href values
for (WebElement link: header_links) {
hrefs.add(link.getAttribute("href"));
}
// visit all the URLs
for (String url: hrefs) {
driver.get(url);
Thread.sleep(1000);
// do some stuff here
}
}
// modified wait method
public WebDriverWait wait_sec(WebDriver driver, int sec) {
return new WebDriverWait(driver, sec);
}
}
This question already has answers here:
NoSuchElementException, Selenium unable to locate element
(3 answers)
Closed 4 years ago.
I am trying to run the below selenium code and I am getting an exception:
package demos;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AmazonLogin {
public static void main(String[] args) throws InterruptedException {
WebDriver driver;
// Go to website and login
driver = utilites.DriverFactor.open("chrome");
driver.get("https://www.amazon.in/your-account");
WebElement loginName = driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[2]/div[2]/a/div/div"));
WebElement emailId = driver.findElement(By.xpath("//*[#id=\"ap_email\"]"));
// WebElement continueButton=driver.findElement(By.id("continue"));
// WebElement password=driver.findElement(By.name("password"));
// WebElement loginButton=driver.findElement(By.id("signInSubmit"));
// WebElement message=driver.findElement(By.className("nav-line-1"));
//
loginName.click();
emailId.sendKeys("aryan.ragavan#gmail.com");
}
}
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such
element:
Unable to locate element: {"method":"xpath","selector":"//*[#id="ap_email"]"}
Selenium is trying to find webelement emailid before it clicks loginName webelement. Please help.
This is because you are trying to read the emailId field before you have clicked on login. Move the following line below loginName.click() statement.
WebElement emailId = driver.findElement(By.xpath("//*[#id=\"ap_email\"]"));
the issue is you are searching for 'app_element' on the main page of amazon.
Introduce yourself to POM implementation here:
https://www.guru99.com/page-object-model-pom-page-factory-in-selenium-ultimate-guide.html
DO-NOT use absolute xpath in any case as you did here:
findElement(By.xpath("/html/body/div[1]/div[2]/div/div[2]/div[2]/a/div/div"));
Here is an example of login logic for amazon:
#Test
public void amazon_login() {
browseToUrl("https://www.amazon.in/your-account");
// select login & security option
WebElement loginAndSecurityBtn = driver.findElement(By.xpath("//div[#data-card-identifier='SignInAndSecurity']"));
// navigate to the next page
loginAndSecurityBtn.click();
// enter email or phone
WebElement emailOrPhoneInput = driver.findElement(By.id("ap_email"));
emailOrPhoneInput.sendKeys("example#email.com");
// click continue btn
WebElement continueBtn = driver.findElement(By.id("continue"));
continueBtn.click();
// enter password
WebElement passwordInput = driver.findElement(By.id("ap_password"));
passwordInput.sendKeys("password");
// login
WebElement loginBtn = driver.findElement(By.id("signInSubmit"));
loginBtn.click();
}
For Amazon Login, You Can Refer This Code . or Below POM(PageobjectModel) Code
package TestId;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
public class NewTest {
WebDriver driver;
#Test
public void f()
{
System.setProperty("webdriver.chrome.driver", "E:\\New Folder\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.amazon.in/your-account");
WebElement e1 = driver.findElement(By.xpath("//*[#id='nav-link-yourAccount']/span[2]"));
WebElement e2 = driver.findElement(By.xpath("//*[#id='nav-flyout-ya-signin']/a/span"));
Actions a1 = new Actions(driver);
a1.moveToElement(e1).click(e2).build().perform();
}
#AfterTest
public void CheckLogin()
{
WebElement e3 = driver.findElement(By.xpath("//*[#id='authportal-main-section']/div[2]/div/div[1]/form/div/div/div"));
WebDriverWait wait = new WebDriverWait(driver, 5);
WebElement e4 = wait.until(ExpectedConditions.visibilityOf(e3));
if(e4.isDisplayed())
{
driver.findElement(By.id("ap_email")).sendKeys("Test#gmail.com");
System.out.println("Email Successfully Passed");
}
}
}
I Used Webdriver Wait because, i Need to Wait Until The Login Page is Loaded and i Used an if-Condition because after The Page is Displayed Pass The Email id.
if You Find Difficultly in Above Use Use Below POM Method.
Amazon Login Using POM:
package POM;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Pageobject
{
WebDriver driver;
public Pageobject(WebDriver driver)
{
this.driver=driver;
}
#FindBy(xpath = "//*[#id='nav-link-yourAccount']/span[2]")
public WebElement Siginpath;
#FindBy(how=How.XPATH,using="//*[#id='nav-flyout-ya-signin']/a/span")
public WebElement clicksignin;
#FindBy(how=How.XPATH,using="//*[#id='authportal-main-section']/div[2]/div/div[1]/form/div/div/div")
public WebElement ElementtobeVisible;
#FindBy(how=How.ID,using="ap_email")
public WebElement Email;
public void Loginpage(String email)
{
Actions a1 = new Actions(driver);
a1.moveToElement(Siginpath).click(clicksignin).build().perform();
WebDriverWait wait = new WebDriverWait(driver, 5);
WebElement e4 = wait.until(ExpectedConditions.visibilityOf(ElementtobeVisible));
if(e4.isDisplayed())
{
Email.sendKeys(email);
}
}
}
Test Case For POM :
package POMtestcase;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import POM.Pageobject;
public class Pomtest
{
WebDriver driver;
#Test
public void Checkvaliduser()
{
System.setProperty("webdriver.chrome.driver", "E:\\New Folder\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.amazon.in/your-account");
Pageobject object = PageFactory.initElements(driver, Pageobject.class); //Calling The Class Here
object.Loginpage("test#gmail.com");//Passing the Mail id
}
}
I want to extract chrome logs in java selenium web driver project. I am using following to launch chromedriver.
> dc = DesiredCapabilities.chrome();
> System.setProperty("webdriver.chrome.logFile","//src//resource//log.txt");
Another similar question has following solution.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ChromeConsoleLogging {
private WebDriver driver;
#BeforeMethod
public void setUp() {
System.setProperty("webdriver.chrome.driver", "c:\\path\\to\\chromedriver.exe");
DesiredCapabilities caps = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(caps);
}
#AfterMethod
public void tearDown() {
driver.quit();
}
public void analyzeLog() {
LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
for (LogEntry entry : logEntries) {
System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
//do something useful with the data
}
}
#Test
public void testMethod() {
driver.get("http://mypage.com");
//do something on page
analyzeLog();
}
}
Solution is not useful for me, as I want to save browser log for every session with the session Id itself.
I am not able to perform the send keys operation while submitting a form using the locator method (Xpath). While submitting the forms or while login I am not able to find the element by using the xpath.
package accomplishment_Tracker;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class ects {
public WebDriver driver;
#BeforeTest
public void openurl(){
//driver =new FirefoxDriver();
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("reader.parse-on-load.enabled",false);
driver = new FirefoxDriver(firefoxProfile);
driver.get("http://66.192.160.50/ects/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println("Website opened succesfully");
}
//LOGIN
#Test
public void login(){
driver.findElement(By.xpath("html/body/div[1]/div/div/div/div[2]/form/fieldset/div[1]/input")).sendKeys("abcde");//("admin");
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div[2]/form/fieldset/div[2]/input")).sendKeys("password");
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div[2]/form/fieldset/div[3]/label/input")).click();
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div[2]/form/fieldset/input")).click();
}
#AfterTest
public void close(){
driver.quit();
}
}
Also how do I find out the frame id as frame(0).......
http://www.ecomnets.com/careers/submit-a-resume/
I am trying to fill in this form and I am not able to fill in the details using the selenium commands.
All Elements of your page are within iframe so you have to first switch to iframe :
Add following before login :
driver.switchTo().frame(0);
So it will be :
public void login(){
driver.switchTo().frame(0);
driver.findElement(By.xpath("html/body/div[1]/div/div/div/div[2]/form/fieldset/div[1]/input")).sendKeys("abcde");//("admin");
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div[2]/form/fieldset/div[2]/input")).sendKeys("password");
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div[2]/form/fieldset/div[3]/label/input")).click();
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div[2]/form/fieldset/input")).click();
}
I just checked , it should work now for you.
I am using Selenium 2.
But after running following code, i could not able to type in textbox.
package Actor;
import org.openqa.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.junit.*;
import com.thoughtworks.selenium.*;
//import org.junit.Before;
public class Actor {
public Selenium selenium;
public WebDriver driver;
#Before
public void setup() throws Exception{
driver = new FirefoxDriver();
driver.get("http://www.fb.com");
}
#Test
public void Test() throws Exception{
//selenium.type("id=gs_htif0", "test");
System.out.println("hi");
// driver.findElement(By.cssSelector("#gb_1 > span.gbts")).click();
selenium.waitForPageToLoad("300000000");
WebElement email=driver.findElement(By.id("email"));
email.sendKeys("nshakuntalas#gmail.com");
driver.findElement(By.id("u_0_b")).click();
}
#After
public void Close() throws Exception{
System.out.println("how are you?");
}
}
This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.
WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("your#email.here");
The reason for NullPointerException however is that your variable driver has never been started, you start FirefoxDriver in a variable wb thas is never being used.
Thanks Friend, i got an answer. This is only possible because of your help. you all give me a ray of hope towards resolving this problem.
Here is the code:
package facebook;
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;
public class Facebook {
public static void main(String args[]){
WebDriver driver = new FirefoxDriver();
driver.get("http://www.facebook.com");
WebElement email= driver.findElement(By.id("email"));
Actions builder = new Actions(driver);
Actions seriesOfActions = builder.moveToElement(email).click().sendKeys(email, "gati.naveen#gmail.com");
seriesOfActions.perform();
WebElement pass = driver.findElement(By.id("pass"));
WebElement login =driver.findElement(By.id("u_0_b"));
Actions seriesOfAction = builder.moveToElement(pass).click().sendKeys(pass, "naveench").click(login);
seriesOfAction.perform();
driver.
}
}
You should replace WebDriver wb = new FirefoxDriver(); with driver = new FirefoxDriver(); in your #Before Annotation.
As you are accessing driver object with null or you can make wb reference variable as global variable.
Try this :
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys("emal#gmail.com");
Another way to solve this using xpath
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath(//*[#id='email'])).sendKeys("your#email.here");
Hope that will help. :)
You can use JavaScript as well, in case the textfield is dithered.
WebDriver driver=new FirefoxDriver();
driver.get("http://localhost/login.do");
driver.manage().window().maximize();
RemoteWebDriver r=(RemoteWebDriver) driver;
String s1="document.getElementById('username').value='admin'";
r.executeScript(s1);