Invalid selector exception for clicking an element using Selenium with Cucumber for W3Schools site - selenium

I am trying with the following Selenium Code using Cucumber for W3Schools site. When I click on "Try it yourself" button then it navigates to another page opening different window and the window control also goes to the new window opened. So,In the new window opened, if i click the run button, it throws an exception:
invalid Selector
code:
//This clicks on the Try it yourself button
#FindBy(how=How.XPATH,using="//*[#id=\"main\"]/div[4]/p/a")
private WebElement TryItYourself;
public void TryItYourSelfClick()
{
TryItYourself.click();
}
//Now,a new window opens up where I want to click on Run Button
#FindBy(how=How.LINK_TEXT,using="Run >>")
private WebElement RunButton;
public void RunClick()
{
RunButton.click();
}
Calling Run Method
#Then("^a new window should appear$")
public void a_new_window_should_appear() {
System.out.println("Run button before Clicking");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
obj1.RunClick();
System.out.println("Run after clicking");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Set <String> handle=driver.getWindowHandles();
String firstWinHandle=driver.getWindowHandle();
String WinHandle=handle.iterator().next();
if(WinHandle!=firstWinHandle)
{
driver.switchTo().window(WinHandle);
System.out.println("Working for new window opened");
}
}
why this invalid selector exception is coming?
HTML code:
<div class="w3-bar w3-light-grey" style="border-top:1px solid #f1f1f1;overflow:auto">
<a id="tryhome" href="https://www.w3schools.com" target="_blank" title="w3schools.com Home" class="w3-button w3-bar-item topnav-icons fa fa-home" style="font-size:28px;color:#999999;margin-top:-2px"></a>
<button class="w3-button w3-bar-item w3-green w3-hover-white w3-hover-text-green" onclick="submitTryit(1)">Run »</button>
<span class="w3-right w3-hide-medium w3-hide-small" style="padding:8px 8px 8px 8px;display:block"></span>
<span class="w3-right w3-hide-small" style="padding:8px 0;display:block;float:right;"><span id="framesize">Result Size: <span>433 x 439</span></span></span>
</div>

I'm not familiar with cucumber, but does it have an option to use cssSelector?
I looked at the button and found
body .trytopnav button
as a valid selector.

This error message...
invalid Selector Exception
...implies that the how=How.LINK_TEXT,using="Run >>" was not a valid selector.
The main issue is the element is not a LINK_TEXT but a <button> tag with text as Run ».
Solution
Change the Locator Strategy as follows:
#FindBy(how=How.XPATH,using="//button[contains(.,'Run »')]")
//or
#FindBy(how=How.XPATH,using="//button[contains(.,'Run')]")
private WebElement RunButton;

look here https://www.seleniumhq.org/exceptions/invalid_selector_exception.jsp we need to avoid using >> as possible, so try to use another locator by avoiding these

Related

Selenium webdriver wait doesn't seem to work in case of overlay

There is an overlay ( a grey color translucent screen ) that comes up when ever one clicks Login button and it stays for few seconds. Because of this, selenium web driver isn't able to find the elements as this overlay kinds of hides them for a while or at least that is what looks to me. How can I handle this? I don't find Thread.sleep to be an efficient way here.
I tried -
public void login(){
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.invisibilityOfElementLocated((By.id("ajax-overlay"))));
wait.until(ExpectedConditions.elementToBeClickable((By.id("okbutton))));
driver.findElement(By.id("username)).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("admin123");
driver.findElement(By.id("okbutton")).click();
wait.until(ExpectedConditions.invisibilityOfElementLocated((By.id("ajax-overlay"))));
}
but nothing seems to work and I still get error -
org.openqa.selenium.WebDriverException: unknown error: Element <button id="loginDialog:okButton" name="loginDialog:okButton" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-panel-titlebar-icon synchronous" onclick="PrimeFaces.ab({source:'loginDialog:okButton',process:'loginDialog:okButton loginDialog:username loginDialog:password loginDialog:okButton',update:'startingCashFocus loginDialog:dialogFocus loginDialog:lblPassword loginDialog:lblUsername loginDialog:messages',oncomplete:function(xhr,status,args){handleLoginAttempt(xhr, status, args, loginWidget, null); ;}});return false;" tabindex="1" type="submit" role="button" aria-disabled="false">...</button> is not clickable at point (931, 250). Other element would receive the click: <div id="ajax-overlay" class="ui-blockui ui-widget-overlay ui-helper-hidden eternal" style="display: block;"></div>
Also, there is no way to find out the overlay id and thankfully, selenium gave it in its error details.
Try to click element with one of the following method, which will solve this Exception :
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.id('okbutton'))).click().perform();
OR
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", driver.findElement(By.id('okbutton')));

Selenium Button Click() or Submit()?

Need help on following scenario(using Java):
Doing it manually like this: after filling in some info in a parent page, clicking Continue button on it,
<INPUT TYPE='button' VALUE='Continue' onClick='sendForm()'>
A child window(UserConfirmationPage) pops up with those info from its parent window, clicking the Continue button on the child page, posting the data to server.
<FORM NAME='userConf' ACTION='user.jsp' METHOD='post'>
Do you want to continue?<BR>
<INPUT TYPE='button' VALUE='Continue' onClick='createUser()'>
</FORM>
However, when I do it using Selenium Web Driver, on the parent page,
btnContinue.submit()
a child page pops up with those info from parent page just like what I got when I do it manually but parent does not exist any more. While using
btnContinue.click()
a blank child page is opened without getting any info from parent page and it also complains "session is lost".
I also tried:
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].click();",btnContinue);
and
new Actions(driver).moveToElement(driver.findElement(By.xpath("//input[#value='Continue']"))).click().perform();
but nothing works.
It seems that neither Submit() nor Click() could simulate what was done manually. Any idea?
Thanks a lot in advance!
You did not specify the language, so I assume you're using JAVA:
// since new tab has been opened - need to switch to this tab
// get a list of the currently open windows
Set<String> allTabs = driver.getWindowHandles();
// save the window handle for the current window
String programTab = driver.getWindowHandle();
// switching to the Save tab
String saveTab = ((String) allTabs.toArray()[1]);
driver.switchTo().window(saveTab);
// set timeout
// Click button
driver.findElement(By.id("buttonId")).click();
// set timeout
// switch back to the program tab
driver.switchTo().window(programTab);
Try this it is simplest and easiest code which help you to understand Parent and child scenario.
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://demo.guru99.com/popup.php");
driver.findElement(By.xpath("html/body/p/a")).click();
// return the parent window name as a String
String parentWindow=driver.getWindowHandle();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Pass a window handle to the other window
for(String childWindow: driver.getWindowHandles())
{
System.out.println("child");
//switch to child window
driver.switchTo().window(childWindow);
//find an element and print text of it
WebElement textLabel=driver.findElement(By.xpath("html/body/div[1]/h2"));
System.out.println(" text: "+textLabel.getText());
driver.close();
}
System.out.println("Come to parent window");
//switch to Parent window
driver.switchTo().window(parentWindow);
//find an element and print text of it
WebElement logotext=driver.findElement(By.xpath("html/body/div[1]/h2"));
System.out.println("text: "+logotext.getText());
driver.close();
}

Selenium WD - southwest.com

I am constantly getting "No Such Element Exception" for "First Name" test box
Below is my code:
public class southwestSignUpSave {
WebDriver oBrw;
#Before
public void loadwebsite (){
oBrw = new FirefoxDriver();
oBrw.manage().window().maximize();
oBrw.get("https://southwest.com");
oBrw.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void signUpAndSave(){
oBrw.findElement(By.partialLinkText("OFFERS")).click();
oBrw.findElement(By.partialLinkText("Sign")).click();
//oBrw.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebDriverWait oWait = new WebDriverWait(oBrw, 30);
oWait.until(ExpectedConditions.presenceOfElementLocated(By.id("FIRST_NAME")));
oBrw.findElement(By.id("FIRST_NAME")).clear();
oBrw.findElement(By.id("FIRST_NAME")).sendKeys("abc");
oBrw.findElement(By.id("LAST_NAME")).clear();
oBrw.findElement(By.id("LAST_NAME")).sendKeys("asd");
oBrw.findElement(By.id("EMAIL")).clear();
oBrw.findElement(By.id("EMAIL")).sendKeys("abc#asd.com");
new Select(oBrw.findElement(By.id("HOME_AIRPORT"))).selectByVisibleText("Akron/Canton, OH - CAK");
oBrw.findElement(By.id("IAN")).click();
}
}
I tried to use id and name.
where am I going wrong. I am new to Selenium WD
U can try finding the element using xpath. For that u need to install the firepath plugin in firefox and then inspect the element using firepath.
oBrw.findElement(By.xpath("copy paste the xpath here")).clear();
I would also recommend loading the driver using System property inside loadwebsite() method.
System.setProperty("webdriver.firefox.driver", "//your driver path");
oBrw=new FirefoxDriver();
if the Sign page opens in a new tab/window then u need to navigate to that tab/window because Selenium by default stays in the opening tab. To navigate u need to add the following lines of code after clicking on "Sign"-
Set<String> s=wd.getWindowHandles();
Iterator<String> it=s.iterator();
it.next();//control goes to 1st default tab
String str=it.next().toString();//control goes to the next tab
oBrw.switchTo().window(str);//driver switches to the new window/tab.
if the element is present inside a frame then also u need to switch to that frame first before finding element inside it. Below is the code-
WebElement web=oBrw.findElement(By.xpath("copy paste your frame xpath"));
oBrw.switchTo.frame(web);
now try to find the element present in the new tab/window.
FIRST NAME input text field is inside iframe. Check the below piece of HTML.
<iframe frameborder="0" src="https://luv.southwest.com/servlet/formlink/f?kOHpjQACAY" onload="scroll(0,0);" verticalscrolling="no" horizontalscrolling="no" scrolling="no" title="Click 'n Save signup form"></iframe>
<html dir="ltr">
<head>
<body>
<p>
<span class="required">*Required</span>
</p>
<div class="clear"></div>
<form id="cnsForm" onsubmit="return validateForm();" action="https://luv.southwest.com/servlet/campaignrespondent" method="POST">
<div class="form_field first_name">
<label for="first_name">
<input id="FIRST_NAME" type="text"=""="" maxlength="25" size="22" name="FIRST_NAME">
</div>
...
Hence selenium is unable to find out the element. Here we need to explicitly switch to iframe as below. Insert below code snippet before you find FIRST_NAME. (You can insert well formatted xpath of iframe. I just grabbed it from firebug.)
WebElement iframeSwitch = oBrw.findElement(By.xpath("/html/body/div[1]/div[3]/div[2]/div[1]/div/div/div[4]/div/div/div/div[3]/iframe"));
oBrw.switchTo().frame(iframeSwitch);
That Text box is inside an iFrame, so you need to switch to that iFrame first then try findElement method to locate textbox.
oBrw.findElement(By.partialLinkText("OFFERS")).click();
oBrw.findElement(By.partialLinkText("Sign")).click();
oBrw.switchTo().defaultContent();
oBrw.switchTo().frame(0);
WebElement id = oBrw.findElement(By.name("FIRST_NAME"));
id.sendKeys("USERNAME");
Hope this helps.

how do i click drop down menu using Selenium?

i'm trying to upload some sonar ruleset files to multiple sonars.
i want to get help by web ui automator using Selenium.
i wrote some java code but it still doesn't work.
*added comment
bellowed code works on chrome driver but it doesn't work on safari driver.
please tell me how to modify code to work for multiple browser.
here is my code
public void openQualityProfiles() {
String linkTextSettings = "Settings";
String cssSelector = ".dropdown-menu > ul > li > a";
WebElement settings = waitForElement(By.linkText(linkTextSettings));
settings.click();
WebElement qualityProfiles = waitForElement(By.cssSelector(cssSelector));
qualityProfiles.click();
}
public WebElement waitForElement(By locator) {
WebElement target = null;
WebDriverWait wait = new WebDriverWait(driver, 10);
target = wait.until(ExpectedConditions.elementToBeClickable(locator));
return target;
}
and here is HTML
Settings
<div id="admin-panel" class="dropdown-menu" style="display: none">
<ul>
<li>Quality Profiles</li>
<li>Configuration</li>
<li>Security</li>
<li>System</li>
If your submenu appears when mouse is over, you can use:
new Actions(driver).moveToElement(yourMenu).build().perform();
or try to click on
driver.findElement(By.className("link-more")).click();

not able to click on following link using selenium webdriver

I am not able to click on following link using selenium webdriver:
<center>
<a class="xyz" style="" href="/Folder">My Folders</a>
<span></span>
</center>
I am using the code:
abhiFX.findElement(By.partialLinkText("My Folders")).click();
I see these potential problems:
Are you sure that your HTML 'works' at all if you load the page in a browser and click on the link? What's the expected result of the click?
Is your driver abhiFX initialized properly? Does .click() on other elements work well?
Try to use xpath instead:
public void clickElement() {
try {
WebElement element = abhiFX.findElement(
By.xpath("//a[contains(text(),'My Folders')]"));
element.click();
} catch (InvalidSelectorException e) {
throw new AssertionError("[FAIL] Click Element: Xpath is invalid.");
} catch (NoSuchElementException e) {
throw new AssertionError(
"[FAIL] Click Element: Unable to locate element");
}
}