Selenium Webdriver & findelement - java

I want to find a element, xpath is like this
"//div[#id='contentPane']/div/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div/div/div/div/div/div[3]/div/div"
and then do "clickAt"
If I use
driver.findElement(By.xpath("//div[#id='contentPane']/div/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div/div/div/div/div/div[3]/div/div");
Actions clicker = new Actions(driver);
clicker.moveToElement(baseElement).moveByOffset(0, 0).click().perform();
I receive Exception "Element not found".
What I'm doing wrong?

The use of such long xpaths will cause test cases to fail,a new div can be added or removed dynamically.There should be some part of the id which remains constant.
For example in id = "someString_1234",if 'someString' remains constant and rest keeps changing,you can use symbols like id*='someString' to locate it.
You can refer this discussion for more info.

Instead of
driver.findElement(By.xpath("//div[#id='contentPane']/div/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div/div/div/div/div/div[3]/div/div");
Try this code:
driver.findElement(By.id("contentPane");

Related

ExpectedConditions.or function not working as expected

I have to test an e-shop. The users can add items to their cart.
When the cart is empty, a special section with id "empty-basket" is created. If the cart is not empty, this section's id becomes "basket".
I use Java and Selenium 3.9
These are my two selectors
#FindBy(how = How.CSS, using = "#empty-basket > section")
private WebElement conteneur_panier_vide;
#FindBy(how = How.CSS, using = "#basket > section:nth-child(1)")
private WebElement conteneur_panier_non_vide;
To check if the bloc containing the elements is well formed, I check if there is one of the sections described above. I use this piece of code to do so:
this.wait.until(
ExpectedConditions.or(
ExpectedConditions.visibilityOf(conteneur_panier_vide),
ExpectedConditions.visibilityOf(conteneur_panier_non_vide)
)
);
However, this gives me an error
org.openqa.selenium.TimeoutException: Expected condition failed: waiting for at least one condition to be
valid
Surprised, I tried this:
this.wait.until(ExpectedConditions.visibilityOf(conteneur_panier_vide))
on a page with an empty basket. It works, the WebElement is found.
I then tried this:
this.wait.until(
ExpectedConditions.or(
ExpectedConditions.visibilityOf(conteneur_panier_vide),
)
);
And it works as well. It means that adding a non-existing element to the 'or' breaks it, which is exactly the opposite of what it should be.
Does anyone have an idea of why my code is not working?
Edit: SOLVED!
The problem was that the element I was looking for was not on the page when the or function is called, resulting in the malfunctioning mentioned above.
I simply put
this.wait.until(ExpectedConditions.urlContains(MY_CART_URL));
which ensures the presence of one of the two sections.
There are two things you can do to clean this up:
Create a CSS selector that matches both elements
Use ExpectedConditions.visibilityOfElementLocated(By.css(...)) instead of the more complicated or
// CSS selectors can be separated by a comma (,)
String cssSelector = "#empty-basket > section, #basket > section:nth-child(1)";
this.wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(cssSelector));
Your original problem was that using the conteneur_panier_vide and conteneur_panier_non_vide attributes was causing Selenium to attempt to fetch them. You just need to wait for the appearance of either element.
Have you instantiated your wait object? You didn't specify your environment but here's what I do in
C#
var wait = new WebDriverWait( Driver, TimeSpan.FromSeconds( 10 ) );
Java
WebDriverWait wait = new WebDriverWait(driver, 20);
I did solve the problem, and edited the question to let people know.
TL;DR:
I needed some delay before calling the or function, and did so by waiting for the URL to be the right one.

Using the Element sendkeys(keys.ENTER) in an automated test does not work as expected

I'm running an automated test, where I need to first type the content into a field and then enter the value in the field and then enter the intermediate button. There is a problem that occurs when this operation is performed twice. Inter will be lost and my test will fail.
I wanted to know the following items in the Selenium 3.6.0 bug?
WebElement enterPage = driver.findElement(By.name("inputItem"));
enterPage.clear();
enterPage.sendKeys("5");
enterPage.sendKeys(Keys.ENTER);
Meanwhile, the use of Thread and wait does not help.
Please try below code,
WebElement enterPage = driver.findElement(By.name("inputItem"));
enterPage.clear();
enterPage.sendKeys("5");
driver.sendKeys(Keys.ENTER);
You can try by usign Actions. See the code below.
Actions actions = new Actions(driver);
WebElement enterPage = driver.findElement(By.name("inputItem"));
enterPage.clear();
actions.sendKeys("5").build().perform();
actions.sendKeys(Keys.ENTER).build().perform();

Getting error Element not found in the cache - perhaps the page has changed since it was looked up, when i am trying to select an option from dropdown

I am getting error "Element not found in the cache - perhaps the page has changed since it was looked up" , when i am trying to select an option from dropdown. Please find my code below
WebElement searchID=driver.findElement(By.xpath("ctl00$ContentPlaceHolderView$ctlRegistration$DropDownList1"));
List <WebElement> searchOptions=searchID.findElements(By.tagName("option"));
for(int i=0;i<searchOptions.size();i++)
{
if(i==1)
{
String searchIdDropdown=searchOptions.get(i).getText().toString().trim();
System.out.println(searchIdDropdown);
driver.findElement(By.name("ctl00$ContentPlaceHolderView$ctlRegistration$DropDownList1")).click();
driver.findElement(By.name("ctl00$ContentPlaceHolderView$ctlRegistration$DropDownList1")).sendKeys(searchIdDropdown);
driver.findElement(By.name("ctl00$ContentPlaceHolderView$ctlRegistration$DropDownList1")).submit();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.name("ctl00$ContentPlaceHolderView$ctlRegistration$TextBox1']")).sendKeys(Keys.TAB);
driver.findElement(By.name("ctl00$ContentPlaceHolderView$ctlRegistration$TextBox1")).sendKeys(this.getProperties(Country+"_"+UserType+"_Registration_User1"));
driver.findElement(By.name("ctl00$ContentPlaceHolderView$ctlRegistration$TextBox1")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
Please let me know how this error can be resolved.
Thanks in Advance,
Manasa.
So a few things to note:
If you can get them I would use IDs or Names for the elements you are
trying to find. Hopefully those will be much cleaner than the xpath.
You are rerunning your find element multiple times when you could
just use a WebElement and make your code far more readable.
I would try to use Explicit waits vs the implicit ones.
So this is my best suggestion of a starting point based on the code you provided.:
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement searchID = driver.findElement(By.xpath("ctl00$ContentPlaceHolderView$ctlRegistration$DropDownList1"));
List<WebElement> searchOptions=searchID.findElements(By.tagName("option"));
for(WebElement option : searchOptions)
{
if(option.getText().equals("drop down name"))// or since you were looking for the index of 1 regardless you can just do just to a .get(1) from the collection directly.
{
wait.until(ExpectedConditions.visibilityOf(option));
option.click();
WebElement textbox = driver.findElement(By.name("ctl00$ContentPlaceHolderView$ctlRegistration$TextBox1"));
wait.until(ExpectedConditions.visibilityOf(textbox));
textbox.sendKeys(this.getProperties(Country+"_"+UserType+"_Registration_User1"));
textbox.click(); //is this supposed to be a submit of some sort?

Webdriver test doesn't select option from dropdown

i have a registration form for checkout,I have to select a state from drop down,for which i have written a script:
WebElement wb = driver.findElement(By.name("user_data[s_state]")) ;
Select selwb = new Select(wb) ;
selwb.selectByValue("KR");
driver.findElement(By.name("dispatch[checkout.update_steps]")).click() ;
but after executing this script,it is not selecting given value from dropdown.hence i am unable to proceed on next step. Plz help me out....
I can give you a suggestion since I have worked with Selenium webdriver for sometime. The webdriver executes very fastly. Selenium driver doesnt take care whether the page loaded or not. So I recommend you to add code just before the click/selection events to make sure that the page loaded completely. There are options like waitForPageLoad() or checkifComponent exist to make sure that page is loaded properly before the events are triggered. Hope this will help you.
If any wait doesn't help - like suggested before - try to select eg. by index or text.
I've had such wired cases where one of ByValue/ByText/ByIndex method didn't work although others did with particular dropdown.
If you are about to select the drop down use the following:
First make the webdriver wait
Then try choosing the element with the help of
driver.findElement(By.xpath("xpath of the value").select
OR
you can use like the following:
new WebDriverWait(driver,30).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("the xpath of the value"))).click();

Set focus on WebElement?

i'm currently testing the GUI of my application, and i wanted to know if it's possible to set the focus to a WebElement ?
I'm using Selenium 2.0 and the webdriver.
So i'm looking for something like that : driver.findElement(xxxx).setfocus();
Thank you.
EDIT :
I've alreardy tested that kind of tricky things
// getting the element WebElement
eSupplierSuggest = driver.findElement(By.xpath("..."));
//get le location and click
Point location = eSupplierSuggest.getLocation();
new Actions(driver).moveToElement(eSupplierSuggest, location.x, location.y).click();
//or
//directly perform
new Actions(driver).moveToElement(eSupplierSuggest).click().perform();
i red somewhere that the click focus the element, but in my case, nothing works. lol
PS : this is a sub-question of that original post Click on a suggestbox, webdriver
I normally send an empty key to the element so it gets focused. So for example:
element.send_keys ""
In order to set focus on the element you can use executeScript method as described below :
JavascriptExecutor js;
js.executeScript ("document.getElementById('x').focus()");
Once the focus is set you can easily use send_keys provided by webdriver api.
Try using cssSelector for the autosuggestion click as shown below and let me know if you are still facing the issue.
// supplier ops, i find and type data into the input
WebElement eSupplier = driver.findElement(By.id("supplier:supplierOps_input"));
eSupplier.sendKeys("OPS1");
sleep(5); // wait the suggestbox
// i find the suggestbox
WebElement eSupplierSuggest = driver.findElement(By.cssSelector("css path of that specific value in the auto suggestion box"));
eSupplierSuggest.click();
sleep(5); // wait the refresh for the next field supplierAddress
There is no function in the WebDriver API to set focus on an element.
If you want to do it you would have to write some JavaScript to set focus and then use a JavaScriptExecutor to run the JavaScript.
Make sure, that you are not changing the frame....
Other wise .click() should do the trick

Categories