I'm new to the programming world so I wouldn't know how to fix this.
`#Test
public void LoginEmail() {
driver.findElement(By.id("email_button")).sendKeys("xxxxxxxx#gmail.com");`
At driver.findElement , driver is underlined red. When I hover over it these are my options.
Couldn't copy the options, so I took a screenshot:
you should initialize it first :
try {
WebDriver driver = new AndroidDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
} catch (Exception e) {
e.printStackTrace();
}
AndroidDriver driver = new AndroidDriver(new URL("localhost:4723/wd/hub"), cap);
This should be a class or local accessibility. Declare as a class object i.e in this text fixture or in the parent class which is inherited by this class or initialize locally i.e. in the test method.
Related
I am trying to open a link in a new tab using selenium java automation code.
Initially i tried with actions class but it wasn't working. Later i tried using the Keys to automate the same thru keyboard actions and it worked. But i wanted to know why am i unable achieve the same with Actions class. Just wanted to if i am doing anything wrong here or is Actions class not suitable for this.
Below is the code snippet i have written.
public class InterviewQuestion {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//System.out.println(System.getProperty("user.dir")+"\\"+"chromedriver.exe");
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\"+"chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.co.in/");
driver.manage().window().maximize();
WebElement GoogleSearchTextBox = driver.findElement(By.xpath("//input[#title='Search']"));
GoogleSearchTextBox.sendKeys("test automation");
GoogleSearchTextBox.sendKeys(Keys.ENTER);
**boolean useActionsClass = false,useKeys = true;**
// finding the required element to be clicked
WebElement RequiredSearchResult = driver.findElement(By.xpath("//div[#class='EIaa9b']/div[1]/div[2]/a"));
if(**useActionsClass**)
{
Actions actions = new Actions(driver);
//actions.moveToElement(RequiredSearchResult).build().perform();
Thread.sleep(5000);
actions.moveToElement(RequiredSearchResult).contextClick(RequiredSearchResult).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
}
if(useKeys)
{
Thread.sleep(5000);
String s = Keys.chord(Keys.CONTROL,Keys.ENTER);
RequiredSearchResult.sendKeys(s);
Set<String> windows = driver.getWindowHandles();
Iterator itr = windows.iterator();
Object FirstWindowHandle = itr.next();
Object SecondWindowHandle = itr.next();
driver.switchTo().window((String) SecondWindowHandle);
Thread.sleep(5000);
//driver.switchTo().window((String) FirstWindowHandle);
}
//driver.quit();
}
}
First, get the link with the help of href attribute from your RequiredSearchResultLink element. once you have the link, use selenium 4 driver.switchTo().newWindow(WindowType.TAB); method to open a new tab. Once the tab is open, just pass your get method, the url which you got from your link field.
If you are not using selenium 4, I will strongly suggest using it, as it will remove lots of unnecessary code from the action class.
Selenium 4 dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
Code with Selenium 4:
driver.get("https://www.google.co.in/");
driver.manage().window().maximize();
WebElement GoogleSearchTextBox = driver.findElement(By.xpath("//input[#title='Search']"));
GoogleSearchTextBox.sendKeys("test automation");
GoogleSearchTextBox.sendKeys(Keys.ENTER);
WebElement RequiredSearchResultLink = driver.findElement(By.xpath("//div[#class='EIaa9b']/div[1]/div[2]/a"));
String href = RequiredSearchResultLink.getAttribute("href");
driver.switchTo().newWindow(WindowType.TAB);
driver.get(href);
Thread.sleep(10);
driver.quit();
}
3 things you need to
Copy the link you need to open in new tab
Open new tab
Paste your link
driver.switchTo().newWindow(WindowType.TAB);
driver.get("your new lin");
I have tried my best to write a login script in Selenium for the following site https://www.topmba.com/app. Here is my code:
public class TopMba {
String driverPath = "/usr/bin/chromedriver";
WebDriver driver;
String username = "test#gmail.com"; // Change to your username and passwrod
String password = "12345";
// This method is to navigate topmba URL
#BeforeClass
public void init() {
System.setProperty("webdriver.chrome.driver", driverPath);
driver = new ChromeDriver();
driver.navigate().to("https://www.topmba.com");
}
// To log in topmba
#Test
public void login() {
driver.findElement(By.className("tm-user")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.switchTo().frame(driver.findElement(By.xpath("//*[#id=\"tm-modal-frame-nvtfa7vvbm\"]")));
driver.findElement(By.id("edit-user")).sendKeys(username);
driver.findElement(By.id("edit-pass")).sendKeys(password);
driver.findElement(By.id("edit-submit")).click();
driver.switchTo().defaultContent();}
#AfterClass
public void quit() {
driver.close();
}
Here is the Exception :
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id="tm-modal-frame-nvtfa7vvbm"]"}
Use the below code:
driver.get("https://www.topmba.com");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String parentWindowHandle = driver.getWindowHandle();
driver.findElement(By.className("tm-user")).click();
WebElement iframe = driver.findElement(By.xpath("//iframe[contains(#src,'app/sso/user/login')]"));
driver.switchTo().frame(iframe);
driver.findElement(By.id("edit-name")).sendKeys(username);
driver.findElement(By.id("edit-pass")).sendKeys(password);
driver.findElement(By.id("edit-submit")).click();
driver.switchTo().window(parentWindowHandle);
There are a couple of things you need to take care as follows :
To click on the icon with tooltip as Login you have used :
driver.findElement(By.className("tm-user")).click();
If you look at the HTML this Locator Strategy identifies the element uniquely but for a more focused click you need to target the <span> tag which is within an <a> tag which is within the <li> tag with the class attribute you have used. Of-coarse you have induce WebDriverWait.
Once the Sign In Dialog Box opens up you will observe the login fields are within an <iframe>. So you have to induce WebDriverWait for both the cases, once for the frame to be available and for the desired element to be clickable and you can use the following solution :
Code Block :
System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.topmba.com");
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("li.tm-user>a.tmba-user>span.fa-img-icons.fa-img-user"))).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[#src='/app/sso/user/login']")));
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.input-block-level.form-text.required.form-control#edit-name"))).sendKeys("khawar");
driver.findElement(By.cssSelector("input.input-block-level.form-text.required.form-control#edit-pass")).sendKeys("khawar");
driver.findElement(By.cssSelector("button.btn.btn-warning.btn-block.button.js-form-submit.form-submit#edit-submit")).click();
Browser Snapshot :
I have my simple selenium program that validate if the value search box in the google is equal to hello world but i got this error:
Exception in thread "main"
org.openqa.selenium.NoSuchElementException: no such element: Unable to
locate element: {"method":"name","selector":"q"}....
Here's my complete code
public class SimpleSelenium {
WebDriver driver = null;
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowserInChrome();
ss.getPage();
ss.listenForHelloWorld();
ss.quitPage();
}
private void openBrowserInChrome(){
System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");
driver = new ChromeDriver();
}
private void quitPage() {
driver.quit();
}
private void getPage() {
driver.get("http://www.google.com");
}
private void listenForHelloWorld() {
WebElement searchField = driver.findElement(By.name("q"));
int count = 1;
while (count++ < 20) {
if (searchField.getAttribute("value").equalsIgnoreCase("hello world")) {
break;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Do you wait until the page is ready and element displayed?
I've often got this error when the page is still loading. You could add something like
(MochaJS example, pretty much the same API for JAVA tests)
test.it('should check the field existence', function (done) {
let field_by = By.id(ID_OF_THE_FIELD);
driver.wait(until.elementLocated(field_by,
driver.wait(until.elementIsVisible(driver.findElement(field_by)), TIME_TO_WAIT_MS);
done();
});
You wait until the element is visible. If it failed, the timeout of TIME_TO_WAIT_MS will be raised.
The google search bar will never have "hello world" in it because you haven't typed it in?
Also the search field value doesn't seem to update when you type in a search (if you inspect the element using the Console).
If your just learning I would just write a test like this and the click the search button, then confirm the "hello world" text in the search results:
WebElement searchField = driver.findElement(By.name("q"))
searchField.sendKeys("Hello World")
//Add code to click search button
//Add code to assert results on next page
Also I would completely change your listenForHelloWorld() method and use the built in WebDriver ExpectedConditions:
new WebDriverWait(driver, 10)
.until(ExpectedConditions.textToBePresentInElement(searchField, "Hello World"))
Dear all I am using Selenium EventFiringWebDriver to record the called web driver methods. I recognised that I often get a "StaleReferenceException" while when I just use the HtmlUnitDriver alone I don't have the issue.
I also recognised that the call i.e. "click()" has been performed in the browser although the "StaleElementReferenceException" got thrown.
Has anybody an idea while the EventFiringWebDriver runs into such problems while using the HtmlUnitDriver or FirefoxDriver standalone not?
Could it be that the WebElements get updated by the origin drivers at runtime while the wrapped WebElements of the EventFiringWebDriver not?
Or should we raise this as a bug for the EventFiringWebDriver implementation?
Example code with EventFiringWebDriver - throws StaleElementReferenceException
HtmlUnitDriver driver = new HtmlUnitDriver();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
ExtentReports extent = new ExtentReports ("report.html", true);
ExtentTest logger = extent.startTest("test");
EventFiringWebDriver eventDriver = new EventFiringWebDriver(driver);
eventDriver.register(new MyWebDriverEventListener(logger));
try {
WebElement element = null;
eventDriver.get("https://www.google.com");
element = eventDriver.findElement(By.xpath("//input[#type='text']"));
element.sendKeys("Test");
element.submit();
Thread.sleep(2000);
element = eventDriver.findElement(By.xpath("//div[#id='search']//a"));
String title = element.getText();
// HERE the StaleElementReferenceException get thrown ALTHOUGH the "click" event get processed by the browser, it loads already the page
try {
element.click();
} catch(StaleElementReferenceException ex) {
}
Thread.sleep(2000);
Assert.assertEquals(title, eventDriver.getTitle());
logger.log(LogStatus.PASS,"end","Test passed");
} catch(AssertionError error) {
logger.log(LogStatus.FAIL,"end","Test failed:" + error.getMessage());
throw error;
}
finally {
extent.endTest(logger);
extent.flush();
extent.close();
eventDriver.quit();
}
The same code - just using the HtmlUnitDriver directly, works without any problems
HtmlUnitDriver driver = new HtmlUnitDriver();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
ExtentReports extent = new ExtentReports ("report.html", true);
ExtentTest logger = extent.startTest("test");
try {
WebElement element = null;
driver.get("https://www.google.com");
element = driver.findElement(By.xpath("//input[#type='text']"));
element.sendKeys("Test");
element.submit();
Thread.sleep(2000);
element = driver.findElement(By.xpath("//div[#id='search']//a"));
String title = element.getText();
element.click();
Thread.sleep(2000);
Assert.assertEquals(title, driver.getTitle());
logger.log(LogStatus.PASS,"end","Test passed");
} catch(AssertionError error) {
logger.log(LogStatus.FAIL,"end","Test failed:" + error.getMessage());
throw error;
}
finally {
extent.endTest(logger);
extent.flush();
extent.close();
driver.quit();
}
After studying the stack trace of the stale exception I recognised that the issue comes not directly from the EventFiringWebDriver. It gets thrown by my listener implementation of the WebDriverEventListener while I try to get the tag name of the element after the click has been performed.
For me it looks like that the design of the WebDriverEventListener is not optimal. With other words you may not able to use the passed WebElement in the "afterXXX" methods, otherwise you may risk a stale exception. Instead you should use the "beforeXXX" methods in order to retrieve the details of the elements.
Stacktrace of my StaleElementReferenceException
at org.openqa.selenium.htmlunit.HtmlUnitDriver.assertElementNotStale(HtmlUnitDriver.java:963)
at org.openqa.selenium.htmlunit.HtmlUnitWebElement.assertElementNotStale(HtmlUnitWebElement.java:734)
at org.openqa.selenium.htmlunit.HtmlUnitWebElement.getTagName(HtmlUnitWebElement.java:291)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.openqa.selenium.support.events.EventFiringWebDriver$EventFiringWebElement$1.invoke(EventFiringWebDriver.java:332)
at com.sun.proxy.$Proxy18.getTagName(Unknown Source)
at ch.megloff.test.SimpleExtentReportWebDriverEventListener.afterClickOn(SimpleExtentReportWebDriverEventListener.java:111)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.openqa.selenium.support.events.EventFiringWebDriver$1.invoke(EventFiringWebDriver.java:81)
at com.sun.proxy.$Proxy16.afterClickOn(Unknown Source)
at org.openqa.selenium.support.events.EventFiringWebDriver$EventFiringWebElement.click(EventFiringWebDriver.java:346)
..s
Java Code snippet of "getTagName()" of the underlying HtmlUnit Implementation
public String getTagName() {
assertElementNotStale();
return element.getNodeName();
}
My "Error-prone" listener implementation for this "afterClickOn" Method - the "getTagName()" should not be called after a click has been performed
public class MyWebDriverEventListener extends AbstractWebDriverEventListener {
...
#Override
public void afterClickOn(WebElement element, WebDriver driver) {
// bad implementation, click has been already performed
// so you may risk to have a stale exception in case the
// browser switched already to the other page (DOM got changed)
logEvent("Clicked on tag: " + element.getTagName() + " with href: " + element.getAttribute("href"));
}
}
I was trying to automate the Make My Trip site using Selenium. These are the steps I took:
Search for MakeMyTrip in Google -> Done
Open makemytrip and change country to US -> Done
Click on feedback -> Done
Trying to fill feedback form -> Error
It's saying, unable to find the element.
I have tried the following:
1. Tried finding the element by id
2. Tried finding the element by xpath
//div[#class='feedback-form-container']//form[#id='feedbackForm']//input[#id='field_name_NAME']"
Code:
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseURL = "http://www.google.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void makeMyTriptest() throws Exception {
System.out.println("Entered this loop");
driver.get(baseURL + "/?gws_rd=ssl");
driver.findElement(By.id("lst-ib")).sendKeys("makemytrip");
System.out.println("send keys successful");
driver.findElement(By.linkText("Flights - MakeMyTrip")).click();
driver.findElement(By.id("country_links")).click();
driver.findElement(By.xpath("//*[#id='country_dropdown']//p//a[#href='http://us.makemytrip.com/']")).click();
driver.findElement(By.xpath("//div[#id='webklipper-publisher-widget-container-content-expand-collapse']")).click();
//entering feedback details
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//driver.findElement(By.id("field_name_NAME")).sendKeys("SubbaRao");
driver.findElement(By.xpath("//div[#class='feedback-form-container']//form[#id='feedbackForm']//input[#id='field_name_NAME']")).sendKeys("SubbaRao");
//driver.findElement(By.id("field_email_EMAIL")).sendKeys("test#test.com");
}
The Feedback form is located inside an iframe. You have to switch into it's context:
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//WebElement iFrame = driver.findElement(By.xpath("//*[id='print_ticket_overlayiframe']"));
driver.switchTo().defaultContent();
driver.switchTo().frame("webklipper-publisher-widget-container-frame");
//driver.findElement(By.id("field_name_NAME")).sendKeys("SubbaRao");
driver.findElement(By.xpath("//*[#id='field_name_NAME']")).sendKeys("SubbaRao");
now while you are in the iframe, search for the input
Works for me.