Can't Select Checkbox, Selenium WebDriver - java

I am unable to select a checkbox with Selenium WebDriver in Java.
I tried by Xpath but no result.
WebDriver can't click on element.
I tried with Selenium IDE - recorder, no results.
Here it is - html code for checkbox
I try:
1.
driver.findElement(By.xpath(".//form[#id='placeOrderForm1']/div[#class='terms right']/label")).click();
2.
driver.findElement(By.id("Terms1")).click();
3.
driver.findElement(By.cssSelector("label")).click();
4.
driver.findElement(By.xpath("//div[3]/form/div/input")).click();
Nothing works.
Please help.

Try using JavascriptExecuter Hope this will help
WebElement element = driver.findElement(By.id("Terms1"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", element );

Your code seems correct. Specially this one -
driver.findElement(By.id("Terms1")).click();
It might be possible the element you are clicking is not visible in the page scroll. Try to move to the element first and then click.
Try with this -
WebElement elem = driver.findElement(By.id("Term1"));
Actions action = new Actions(driver).
action.moveToElement(elem).click().build().perform();
Hope this help.

Here is the Answer of your Question:
As you mentioned unable to select a checkbox, actually we don't select the checkbox, we checkmark the checkbox. The checkbox you depicted have an id as Terms1 and name astermsCheck`. So you use either of the locators to checkmark the checkbox as follows:
driver.findElement(By.id("Terms1")).click();
OR
element = driver.findElement(By.name("termsCheck")).click();
Let me know if this Answers your Question.

You can find the element by a unique identifier. In this case, we can use name or id. The better choice is to go with id.
WebElement element = driver.findElement(By.name("termsCheck"));
element.click();
or you can use this one also
driver.findElement(By.id("Terms1")).click();

Related

Is there a better way to programatically select a value from select2 dropdown using selenium WebDriver?

I am using Selenium WebDriver to automate something. It requires filling a form that involves selecting a value from a select2 dropdown. This is the code snippet that I am using-
final By SELECT_DIV = By.id("s2");
click(SELECT_DIV);
final By INPUT = By.cssSelector(".select2-drop-active .select2-input");
waitForVisibilityOfElement(INPUT);
enterCharSequence(INPUT, "someData");
waitForJSandJQueryToLoad(30);//30 seconds
final By LIST_ITEM = By.cssSelector(".select2-drop-active ul.select2-results li.select2-result-selectable");
click(LIST_ITEM);
FYI, there are no unique ids assigned to some of these elements and hence I used css selectors for locating them.
This code works but it sometimes throws a StaleElementReferenceException. This is the error:
org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Selenium version : 2.53
So, I want to know if there is any way I could avoid this. I read a few posts about it but they were not of much help.
Let me know if you need more information. Any help would be appreciated.
'StaleElementReferenceException' means that the element has changed. It is in another div, another span or the its properties changed. Selenium may found it but it changed the very second you tried to click on it.
You need to search for the same element again and wait for it to be clickAble or visible. For example:
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement button =
wait.until(ExpectedConditions.
elementToBeClickable(By.id("btnLogin")));

Xpath issue in element location

I am getting a very long xpath for an element that I selected. Is there anyway to shorten it? This is the xpath I am getting:
//li[#class='menu_men 1-level hasChild']//div[contains(#class,'level-2')]//div[#class='menu-wrapper']//ul[#class='level-2']//li[#class='1-level']//div[#class='level-3']//ul[#class='level-3']//li//a[#class='level-3'][contains(text(),'Socks')]
This is the URL: Calvin Klein Singapore I hovered over 'MEN', the accessories section will appear, than I hover the 'Socks' to get the xPath.
I am getting the following execption in my code and I am wondering if somehow the long xpath could be one of the reasons:
org.openqa.selenium.NoSuchElementException: no such element: Unable to
locate element: {"method":"xpath","selector":"//li[#class='first
menu_men 1-level
hasChild']//div[contains(#class,'level-2')]//div[#class='menu-wrapper']//ul[#class='level-2']//li[#class='1-level']//div[#class='level-3']//ul[#class='level-3']//li//a[#class='level-3'][contains(text(),'Socks')]"}
I am using cropath from within chrome developer tools to get the xPath.
I am new to automation, I really hope someone can advise. Thank you.
#SameerArora this is the code I have to clear the pop up window, as what I had mentioned in the comments below.
//for clearing the popup window
#FindBy(how=How.XPATH,using="//*[starts-with(#id,'popup-subcription-closes-link-')]")
public WebElement newsletterpopup;
public String clickCategory(){
//.....
resusableFunctions.buttonClick(driver, newsletterpopup, "popoup");
}
public void buttonClick(WebDriver driver, WebElement element, String elementName) throws InterruptedException
{
try
{
element.click();
System.out.println("Log: ResuableFunction.buttonClick");
}
catch (org.openqa.selenium.ElementNotInteractableException notInteract)
{}
The element you are looking for can be found using xpath:
WebElement element = driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]"));
However, as the element is not visible directly when you are opening the link, you would be getting NoSuchElementException, so to resolve it you can use javascript click method on the element which directly operates on the div of the page.
Addition to this, i can see that a subscription popup comes when i am opening the page for the first time, so you need to dismiss that popup first(if the popup is present) and then click on the "Socks" element using the JavaScript click method.
Your code should be like:
List<WebElement> closeSubscriptionPopUp = driver.findElements(By.xpath("//a[contains(#id,'popup-subcription-closes-link')]"));
if (closeSubscriptionPopUp.size() > 0) {
closeSubscriptionPopUp.get(0).click();
}
WebElement sockElement = driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", sockElement);
To hovered over 'MEN' >> accessories >> 'Socks' section, You need to use selenium Actions class.
As it is not really possible to first click on men(as it will open other section),
So to hover to sock, you need to chain all of the actions that you want to achieve in one go.
Process should be:
move to men element first
Move to accessories
then move to Socks and click on it.
Note: By using Action class, we can chain all the process in one single go.
As mentioned below
1) First way:
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'MEN')])[2]")))
.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]")))
.click().build().perform();
2) Second way with wait:
WebDriverWait wait= new WebDriverWait(driver, 10);
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'MEN')])[2]"))).build().perform();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//a[contains(text(),'Socks')])[1]")));
action.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]")));
action.click().build().perform();
Try this:
//a[normalize-space(text()) = 'Socks']
I would recommend you to not use such long xpath's and try to write xpath on your own.
Try :
//li[contains(#class,'menu_men')]//a[contains(text(),'Socks')]

click on a button with JQuery

There is somthing wrong with the page I want to test.
My first try:
When I clicked manually on a button, then I will be forwarded normally on the next page.
When I tried to click on the same button with selenium, then I get an error page "Sorry...something gone wrong...blabla". I think this problem can only solve the developer team of the page.
By book = By.cssSelector("#button\\.buchung\\.continue");
//By book = By.cssSelector("button.buchung.continue");
//By book = By.xpath("//*[#id='button.buchung.continue']");
WebElement element= ConfigClass.driver.findElement(book);
element.click();
But I want to try a workaround:
I clicked on the same button with JQuery.
I opened my chrome console and execute the button with:
jQuery('#button\\.buchung\\.continue').click()
How can I execute this JQuery expression in my selenium code?
I tried this, but without success:
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("jQuery('#button\\.buchung\\.continue').click()");
Use $
je.executeScript("$('#button\\.buchung\\.continue').click()");
jQuery("selector") will return you a list.
I think you have to call click() on the element at index 0 (Assuming exactly one element satisfies the selector)
Code:
je.executeScript("jQuery('#button\\.buchung\\.continue')[0].click()");
You were pretty close. If the cssSelector is uniquely identifying the WebElement you can use the following code block :
By book = By.cssSelector("#button\\.buchung\\.continue");
WebElement element= ConfigClass.driver.findElement(book);
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);

WebDriver can't get dropdown menu element (Java)

I write a script on Java for Selenium WebDriver, and I have a problem with selected from dropdown menu.
Here's my locator:
new Select(driver.findElement(By.id("FormElement_select_68_input_input"))).selectByVisibleText("Image");
Here's an error: http://prntscr.com/7jul03
Here's HTML code: http://prntscr.com/7jvou6
Need to select "Image" from this menu, but have an error.
Before I had the error like this, I can't upload file, it was because I need to switch to frame(0).
But here I don't know why I can't select menu "Image" from DropBox.
Your ID is dynamic, so you can't use it. Select will not work in your case, you just need to use two clicks
WebElement dropdown = driver.findElement(By.xpath("//div[#class='select-pad-wrapper AttributePlugin']/input"));
dropdown.click();
WebElement element = driver.findElement(By.xpath("//div[#class='select-pad-wrapper AttributePlugin']/div/ul/li[text()='Image']"));
element.click();
It looks like the element id you're looking for"FormElement_select_68_input_input" doesn't exist in your html, your code sample shows "FormElement_select_283_input_container" as the select box element. Try this:
Select droplist = new Select(driver.findElement(By.Id("FormElement_select_283_input_container")));
droplist.selectByVisibleText("image");
Because it is not Select tag.
Try with below logic
WebElement div = driver.findElement(By.cssSelector("div[id*='FormElement_'] > div > div"));
div.click();
WebElement li = div.findElement(By.xpath(".//ul/li[text()='Image']"));
li.click();
As per HTML code screen, i am expecting Select class (selectByVisibleText etc) does not work. can you do one thing, try to click on required option directly. (may be click on "//div[#class='selectbox-wrapper']/ul/li[#class='selectbox_li'][contains(text(),'Image')]" , check one is it correct or not in firepath)
Let me know the result.. if it does not work, as said above you need to click on that input dropdown box and need to click on that Image.
Thank You,
Murali

Selenium Webdriver - Find dynamic id from li/a

I am trying to select a value(Bellevue) from a li(it looks like a dropdown but it isn't).The problem is that its id changes everytime the page loads.
Here is a screenshot:
This time the id is: ui-id-23,but the number,23,will be changed next time so this will not work.If I expand the <a id="ui-id-23..." I get the name 'Bellevue' but every character surrounded by < strong > < /strong > mark-up.
I can't find it after it's classname because both values from li have the same class,ui-menu-item.
I tried after xpath:"//a[contains(text(),'Bellevue')]" but I get the error:Unable to locate element...
Do you know any solution for this?I am using Selenium Webdriver in Java and TestNG.
Thanks!
Update
So I managed to find that element by using:
WebElement value = driver.findElements(By.cssSelector("a[id^='ui-id-']")).get(3);
value.click(); .
but in my application i am using page objects and i look after elements using #FindBy(how.HOW.....).Do you know how I can use .get(3) with #FindBy?
You want to use a CSS selector on the ID:
a[id^='ui-id-']
This says "Find all of the a elements that have an ID that start with ui-id-"
If you want to find the second item, then do:
driver.findElements(By.cssSelector("a[id^='ui-id-']"))[1]
The [1] will select the second item on the page.
It looks like jQuery uniquId() method is used to populated the id, so it will always start with ui-id-. You can use jQuery selector to select element whose id starts with ui-id-
WebElement webElement = (WebElement) ((JavascriptExecutor) webDriver).executeScript("return $( 'input[id^="ui-id-"]').get(0);");
I would try to use xpath avoiding using of id. For example, //a[#class=''ui-corner-all ui-state-focus ][2]
First get the tag name in which your id attribute has been defined.
WebElement ele = driver.findElement(By.tagName(tagName));
String strId = ele.getAttribute("id").startsWith("ui-id-");
driver.findElement(By.id(strId)).click();

Categories