Webpage: http://www.forbes.com/companies/icbc/
package selenium;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.By.ByTagName;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ForbesTest {
WebDriver driver;
String url;
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_x64_2.53.1\\IEDriverServer.exe");
driver=new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
url="http://www.forbes.com/companies/icbc/";
driver.get(url);
}
#After
public void tearDown() throws Exception {
driver.quit();
driver.close();
}
#Test
public void test() throws InterruptedException {
Thread.sleep(10000);
WebElement tab=driver.findElement(By.className("large"));
Thread.sleep(1000);
String text= tab.getText();
System.out.println(text);
WebElement col1=driver.findElement(By.tagName("dt"));
//Thread.sleep(1000);
String industry= col1.getText();
if(industry.matches("Industry")){
System.out.println(industry);
WebElement col2=driver.findElement(By.tagName("dd"));
//Thread.sleep(1000);
String industryName= col2.getText();
System.out.println(industryName);
}
String forbesWebsite= driver.getCurrentUrl();
System.out.println(forbesWebsite);
WebElement nextPage=driver.findElement(By.className("next-number"));
nextPage.click();
driver.close();
}
}
I want to capture Rank,Company,Country,Sales,Sales Rank,Profit,Rank Profit,Assets,Rank Assets,Market Value,Rank Market Value,Industry,Founded,Company Website,Employees,HQ City,CEO Name,Forbes.com Company Info Page and Year
To get text for Industry :
String industryName= driver.findElement(By.xpath("//*[contains(text(),'Industry')]//following::dd[1]")).getText();
To get text for Founded :
String Founded= driver.findElement(By.xpath("//*[contains(text(),'Founded')]//following::dd[1]")).getText();
So you just need to replace String with required text as below
xpath = //*[contains(text(),'String')]//following::dd[1]
Related
I am getting java.lang.NullPointerException while following Page Object Model with Cucumber. I am not sure what I am doing wrong here, please help me on this
Below is my Test Base Class:
package com.qa.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class TestBase {
public static WebDriver driver;
public static Properties prop;
//public WebDriver initializeWebDriver() throws IOException
public static void initializeWebDriver() throws IOException
{
prop = new Properties();
FileInputStream fis = new FileInputStream("D:\\Automation\\WebAutomation\\src\\main\\java\\com\\qa\\config\\config.properties");
prop.load(fis);
String browserName = prop.getProperty("browser");
//Execute in Chrome
if(browserName.equals("Chrome"))
{
System.setProperty("webdriver.chrome.driver","D:\\Drivers\\chromedriver.exe");
driver=new ChromeDriver();
//driver.manage().window().maximize();
}
//Execute in FireFox
else if(browserName.equals("Firefox"))
{
System.setProperty("webdriver.gecko.driver","D:\\Drivers\\geckodriver-v0.19.1-win64(1)");
driver = new FirefoxDriver();
}
driver.manage().window().maximize();
driver.get(prop.getProperty("appURL"));
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT,TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
return driver;
}
}
Below is my login page Objects Class
package com.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.qa.util.TestBase;
public class LoginPage extends TestBase {
public LoginPage() {
/*super(driver);
this.driver=driver;*/
PageFactory.initElements(driver, this);
}
// Login Page Title
public String validateLoginPageTitle() {
return driver.getTitle();
}
// Welcome text
#FindBy(css=".login-form > h2:nth-child(1)")
WebElement header;
public String loginPageHeaderText() {
return header.getText();
}
}
Below is my Step Def
package com.qa.stepdefinations;
import java.io.IOException;
import org.testng.Assert;
import com.qa.pages.LoginPage;
import com.qa.util.TestBase;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class LoginStepDef extends TestBase {
LoginPage LoginPage = new LoginPage();
#Given("^I launch browser and access the GE URL$")
public void i_launch_browser() throws IOException {
TestBase.initializeWebDriver();
}
#Then("^I am on Login Page$")
public void i_am_on_login_page() {
String expectedLoginPageTile = prop.getProperty("LoginPage_Title");
String actualLoginPageTitle = LoginPage.validateLoginPageTitle();
Assert.assertEquals(actualLoginPageTitle, expectedLoginPageTile);
}
#Then("^I verify header text is displaying$")
public void i_verify_header_text_is_displaying() {
String expectedHeaderText = prop.getProperty("LoginPage_Expected_Header");
String actualdHeaderText = LoginPage.loginPageHeaderText();
Assert.assertEquals(actualdHeaderText, expectedHeaderText);
}
}
The script is working fine for LoginPage.validateLoginPageTitle(); however, I am not sure why it is not working for the next step i.e. LoginPage.loginPageHeaderText();
It seems issue is with your locator, check if it is correct.
#FindBy(css="<b><em>.login-form > h2:nth-child(1)</em></b>")
WebElement header;
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 am fairly new to selenium, and I was trying to use some of the scripts being used in tutorials for my practice. I downloaded all the required .JAR files (Chrome drivers, Selenium Java and Stand Alone server) and added it to the path in Eclipse.
Below is the Code which I am trying to run to access a Weblink and then trying to verify if a user is able to log in successfully or not.
package learnautomation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class practice {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "Mypath\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.gcrit.com/build3/admin/");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin#123");
driver.findElement(By.id("tdb1")).click();
String url = driver.getCurrentUrl();
if (url.equals("http://www.gcrit.com/build3/admin/index.php")){
System.out.println("Successful");
}
else {
System.out.println("Unsuccessful");
}
driver.close();
}
}
While doing this I am getting this error:
"Error occurred during initialization of boot layer
java.lang.module.FindException: Module seleniumnew not found"
Also, import org.openqa.selenium.chrome.ChromeDriver; it says this is not accessible as well when I just hover over it.
try this, just edit paths and package name.
package navi;
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.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Avi {
public static WebDriver driver;
WebDriverWait wait5s = new WebDriverWait(driver,5);
#BeforeClass
public static void setUpClass() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\pburgr\\Desktop\\chromedriver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:\\Users\\pburgr\\AppData\\Local\\Google\\Chrome\\User Data");
driver = new ChromeDriver(options);
driver.manage().window().maximize();}
#Before
public void setUp() {}
#After
public void tearDown() {}
#AfterClass
public static void tearDownClass() {driver.close();driver.quit();}
#Test
public void avi() throws InterruptedException {
driver.get("http://www.gcrit.com/build3/admin/");
wait5s.until(ExpectedConditions.elementToBeClickable(By.name("username"))).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin#123");
driver.findElement(By.id("tdb1")).click();
// wait to resolve the click before checking url
Thread.sleep(1000);
String url = driver.getCurrentUrl();
if (url.equals("http://www.gcrit.com/build3/admin/index.php")){
System.out.println("Successful");
}
else {
System.out.println("Unsuccessful");
}
}
}
How to test or verify check box is selected or not selected by using selenium webdriver java
package newpackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.firefox.*;
import java.util.concurrent.*;
public class Qemr { public static void main(String[]args){
System.setProperty("webdriver.gecko.driver","D:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String baseUrl = "http://192.168.1.3:9091";
driver.get(baseUrl);
WebElement chkPersist = driver.findElement(By.name("remember"));
chkPersist=click();
for(int i=0;i<2;i++){
System.out.println("chkPersist.isChecked()");
}
}
}
yes there are methods available which you can use for ny kind of controls, for eg. for check box you can use isSelected() method which returns boolean value i.e. 0/1
for your scenario
package newpackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.firefox.*;
import java.util.concurrent.*;
public class Qemr {
public static void main(String[]args)
{
System.setProperty("webdriver.gecko.driver","D:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String baseUrl = "http://192.168.1.3:9091";
driver.get(baseUrl);
WebElement chkPersist = driver.findElement(By.name("remember"));
//chkPersist.click();
if(chkPersist.isSelected())
{
System.out.println("Check box is Selected..");
}
}
}
driver.findElement("").isSelected() option is there to check whether Checkbox is selected. you can find solution in your updated code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.firefox.*;
import java.util.concurrent.*;
public class StackOverFlow1
{
public static void main(String[]args)
{
System.setProperty("webdriver.gecko.driver","D:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
String baseUrl="http://192.168.1.3:9091";
driver.get(baseUrl);
boolean chkPersist=driver.findElement(By.name("remember")).isSelected();
if(chkPersist)
{
System.out.println("chkPersist is in selected state");
}
}
}
}
Question : How to test or verify check box is selected or not selected by using selenium webdriver java.
Answer : Yes we can verify webelement is selected or not using isSelected() method
package newpackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.*;
public class Qemr {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "D:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String baseUrl = "http://192.168.1.3:9091";
driver.get(baseUrl);
WebElement chkPersist = driver.findElement(By.name("remember"));
// Verify chkPersist element is Selected or Not ?
if (chkPersist.isSelected()) {
// if chkPersist element is selected then we print message
System.out.println("chkPersist element is already selected");
} else {
// if chkPersist element is not selected then we select / click on chkPersist element
chkPersist.click();
}
}
}
I downloaded the code below and used it for some tests and u=it ran yesterday but since today the code stopped working. My tests are failing now which was not happening before. It throws up an error saying org.openqa.selenium.ElementNotVisibleException: element is not currently visible so cannot interact with element.
package org.openqa.selenium.example;
//import org.openqa.selenium.browserlaunchers.locators.GoogleChromeLocator;
//import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
//import org.openqa.selenium.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.chrome.*;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.Select;
//import org.openqa.selenium.net.UrlChecker;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class KongaUrlTest
{
private WebDriver driver;
private String baseUrl;
//private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception
{
driver = new FirefoxDriver();
baseUrl = "http://www.konga.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testFirefoxWebdriver() throws Exception
{
driver.get(baseUrl);
driver.findElement(By.cssSelector("a.vertnavlink > span")).click();
try
{
assertEquals("Phones & Tablets | Konga Nigeria", driver.getTitle());
System.out.println(driver.getTitle());
}
catch (Error e)
{
verificationErrors.append(e.toString());
}
}
#After
public void tearDown() throws Exception
{
System.out.println(driver.getCurrentUrl());
driver.quit();
}
}
There's a blocking dialog being displayed. It's probably displayed each time Selenium opens a new browser and navigates to that site. Close that dialog first:
driver.get(baseUrl);
try
{
driver.findElement(By.cssSelector(".fancybox-close")).click();
}
catch { }
driver.findElement(By.cssSelector("a.vertnavlink > span")).click();