The import org.openqa.selenium.chrome cannot be resolved - java

On Eclipse, The error red line was showing below the ChromeDriver statement and Line 18 (WebDriver driver = new ChromeDriver). Is that code correct?
Code:
package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
//import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class FirstTestNGFile {
public String baseUrl = "http://demo.guru99.com/test/newtours/";
String driverPath=
"C:\\Users\\manoj\\Documents\\QA\\COURSE\\ChromeDriver94\\chromedriver.exe";
//public WebDriver driver;
#Test
public void f() {
System.out.println("launching chrome browser");
System.setProperty("webdriver.chrome.driver", driverPath);
WebDriver driver = new ChromeDriver();
driver.get(baseUrl);
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
driver.close();
}
}

Yes it looks fine to me.
Additionally, you'd have to import WebDriver as well.
import org.openqa.selenium.WebDriver;
If that still did not work, I would suggest to take WebDriver driver out of #Test
Sample code :
private WebDriver driver;
public String baseUrl = "http://demo.guru99.com/test/newtours/";
String driverPath = "C:\\Users\\manoj\\Documents\\QA\\COURSE\\ChromeDriver94\\chromedriver.exe";
#Test
public void f() {
System.out.println("launching chrome browser");
System.setProperty("webdriver.chrome.driver", driverPath);
driver = new ChromeDriver();
driver.get(baseUrl);
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
driver.close();
}

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
// Few important imports in selenium to look.
// WebDriver interface is important for using methods
get(),getCurrentUrl(),findElement(),close(),quit() etc

Related

Cannot get Java Selenium in headless mode

I've searched around for awhile now and it seems like i just need to add chrome options to get selenium to go into headless mode. I am quite new and i maybe missing something but i've tried the adding the code below into my scripts in to various areas and it doesn't seem to work.
ChromeOptions options = new ChromeOptions();
options.addArguments("window-size=1400,800");
options.addArguments("headless");
I've tried the following
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeOptions;
public class TestPlan {
private static final WebDriver driver = new ChromeDriver();
#BeforeSuite
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", Utils.CHROME_DRIVER_LOCATION);
ChromeOptions options = new ChromeOptions();
options.addArguments("window-size=1400,800");
options.addArguments("headless");
WebDriver driver = new ChromeDriver(options);
WebDriverWait wait = new WebDriverWait(driver, 30);
}
#Test(testName = "Login Page")
public static void wikiLogin() {
driver.get(Utils.WIKI_LOGIN_URL);
WikiLogin wikilogin = new WikiLogin(driver);
wikilogin.loginButton();
}
and
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeOptions;
public class TestPlan {
private static final WebDriver driver = new ChromeDriver();
#BeforeSuite
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", Utils.CHROME_DRIVER_LOCATION);
WebDriverWait wait = new WebDriverWait(driver, 30);
}
#Test(testName = "Login Page")
public static void wikiLogin() {
ChromeOptions options = new ChromeOptions();
options.addArguments("window-size=1400,800");
options.addArguments("headless");
WebDriver driver = new ChromeDriver(options);
driver.get(Utils.WIKI_LOGIN_URL);
WikiLogin wikilogin = new WikiLogin(driver);
wikilogin.loginButton();
}
With no success. Would appreciate some help. Thanks!

I am not able to find elements in selenium [duplicate]

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
}
}

Selenium Webdriver - Java, Browser shows message "ERROR: This page has expired. Please cancel this operation and try again" on button click

When I run the test method runSuite(), everything is fine till the last line of the method:
button.click(); // clicks the button on page
The above statement results in the page expired issue.
I get the following message on the browser window:
ERROR: This page has expired. Please cancel this operation and try again.
I tried playing around browser cache, but that didn't help.
package com.swtestacademy.webdriver;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Timeouts;
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.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.junit.*;
import com.util.MockLoginClient;
import static org.junit.Assert.*;
public class MainTest {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
MockLoginClient.instance().authenticateAsHcrCaseWorker();
//System.setProperty("webdriver.ie.driver","C:/IEDriverServer_x64_3.4.0/IEDriverServer.exe");
//driver = new InternetExplorerDriver();
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
options.addPreference("log", "{level: trace}");
capabilities.setCapability("marionette", true);
capabilities.setCapability("moz:firefoxOptions", options);
capabilities.setCapability(CapabilityType.ELEMENT_SCROLL_BEHAVIOR, 1);
capabilities.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, "applicationCacheEnabled");
System.setProperty("webdriver.gecko.driver", "C:/geckodriver-v0.16.1-win64/geckodriver.exe");
//ProfilesIni profile = new ProfilesIni();
//profile.getProfile("default");
FirefoxProfile ffprofile = new FirefoxProfile();
ffprofile.setPreference("browser.cache.disk.enable", true);
ffprofile.setPreference("browser.cache.memory.enable", true);
ffprofile.setPreference("browser.cache.offline.enable", true);
ffprofile.setPreference("network.http.use-cache", true);
driver = new FirefoxDriver(capabilities);//ffprofile);
//driver.manage().deleteAllCookies();
baseUrl = "http://localhost:8082/";
driver.manage().timeouts().implicitlyWait(3000, TimeUnit.MILLISECONDS);
//driver.manage().timeouts().pageLoadTimeout(10,TimeUnit.SECONDS);
// driver.manage().timeouts().setScriptTimeout(3000,TimeUnit.MILLISECONDS);
driver.get(baseUrl + "/Curam/AppController.do");
}
#Test
public void test() throws Exception {
driver.get(baseUrl + "/Curam/AppController.do");
driver.findElement(By.id("app-sections-container-dc_tablist_DefaultAppSection-sbc_tabLabel")).click();
driver.findElement(By.cssSelector("div.dojoxExpandoIcon.dojoxExpandoIconLeft")).click();
Thread.sleep(1000);
driver.findElement(By.id("dijit_layout_AccordionPane_1_button_title")).click();
driver.findElement(By.cssSelector("#dijit_layout_AccordionPane_1 > ul > li > a.curam-content-pane-single-link")).click();
driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
iterator.next();
}
//driver.switchTo().window(subWindowHandler); // switch to popup window
driver.findElement(By.id("curam_ModalDialog_0"));
driver.findElement(By.className("dijitDialogPaneContent"));
driver.findElement(By.id("curam_ModalUIMController_0"));
driver.findElement(By.className("contentPanelFrameWrapper"));
driver.switchTo().frame("iframe-curam_ModalDialog_0");
driver.findElement(By.tagName("html"));
driver.findElement(By.tagName("body"));
driver.findElement(By.id("content"));
driver.findElement(By.id("mainForm"));
driver.findElement(By.id("modal-actions-panel"));
// driver.findElement(By.xpath("//div[#id='modal-actions-panel']/div[2]/a/span/span/span")).click();
WebElement nxtBtn = driver.findElement(By.id("__o3btn.NEXTPAGE_2"));
Thread.sleep(1000);
nxtBtn.click();
driver.findElement(By.xpath("//div[#id='modal-actions-panel']/div[2]/a[2]/span/span/span")).click();
driver.findElement(By.id("__o3btn.SAVE_0")).click();
}
#After
public void tearDown() throws Exception {
//driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
#Test
public void runSuite() throws InterruptedException {
System.out.println(driver);
WebElement xy = driver.findElement(By.id("app-sections-container-dc_tablist_DefaultAppSection-sbc_tabLabel"));
xy.click();
driver.findElement(By.cssSelector("div.dojoxExpandoIcon.dojoxExpandoIconLeft")).click();
WebElement personSearchLink = driver.findElement(By.linkText("Person…"));
Thread.sleep(1000);
personSearchLink.click();
WebElement appStc = driver.findElement(By.id("DefaultAppSection-stc"));
WebElement djtTab = appStc.findElement(By.className("dijitTabPaneWrapper"));
Thread.sleep(1000);
WebElement tpChldWrapper = djtTab.findElement(By.className("dijitTabContainerTopChildWrapper"));
WebElement lyoutCntntPane = tpChldWrapper.findElement(By.id("dojox_layout_ContentPane_1"));
WebElement tbWrpr = lyoutCntntPane.findElement(By.className("tab-wrapper"));
WebElement noDtlsPnl = tbWrpr.findElement(By.className("no-details-panel"));
WebElement cntntAreaCntnr = noDtlsPnl.findElement(By.className("content-area-container"));
WebElement fstUIMCntrlr = cntntAreaCntnr.findElement(By.id("curam_FastUIMController_1"));
WebElement cntntPnlFrmWrpr = fstUIMCntrlr.findElement(By.className("contentPanelFrameWrapper"));
WebElement iFrameElmnt = cntntPnlFrmWrpr.findElement(By.tagName("iframe"));
driver.switchTo().frame(iFrameElmnt);
WebElement inputText = driver.findElement(By.id("__o3id0"));
Thread.sleep(100);
inputText.sendKeys("24684");
// Thread.sleep(4000);
WebElement button = driver.findElement(By.linkText("Search"));
button.click();
}
}
I could see the issue. This behavior is seen for Firefox and Internet explorer only and not for chrome.
The solution would be to check the default desired capabilities for Chrome driver and set the same for Firefox driver or IE driver.
Easier Solution: Switch to Chrome Driver.

Unable to use PhantomJS driver with Firefox profile in Selenium

I try to use a PhantomJS driver for my Selenium tests but I don't succeed to recover my Firefox profile to avoid me login in the website.
This is my code :
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Stackoverflow {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
System.setProperty("phantomjs.binary.path", System.getProperty("user.dir") + "/lib/phantomjs-2.1.1-windows/bin/phantomjs.exe");
DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
driver = new PhantomJSDriver(capabilities);
driver.manage().window().maximize();
baseUrl = "http://stackoverflow.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testStackoverflow() throws Exception {
driver.get(baseUrl);
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
}
Can you tell me how to set PhantomJS driver ?
You are unable to use a firefox profile with PhantomJS because you're trying to use a firefox profile with PhantomJS... PhantomJS is not firefox, how did you think that was going to work.
Use this code to set the path of the phantomjs driver, Use this and let me know if you facing any issue:
File file = new File("E:\\software and tools\\phantomjs-2.1.1-windows\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
OR
System.setProperty("phantomjs.binary.path", "E:\\software and tools\\phantomjs-2.1.1-windows\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
WebDriver driver = new PhantomJSDriver();

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

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);

Categories