Selenium webdriver:select a "div" from many "div"s that dynamically change the absolute path - selenium

I need some help in selecting a div form many div's that for every session number of div's are changing.
For example:
one time a have the div in that position(absolute path): /html/body/div[97]
other time in that position (absolute path):/html/body/div[160]
and so on...
At a moment only one div is active and the other div's are hidden.
I attached a picture to show the code.
I try the xpath below but doesn't work,I get the error "no such element: Unable to locate element ...
driver.findElement(By.xpath(".//*[#class=\'ui-selectmenu-menu ui-selectmenu-open\']/ul/li[1]")).click();
Picture with html code is here:

XPath is great if you expect the target element to be in the exact location every time the page is displayed. However, CSS is the way to go if the content is constantly changing.
In the example below I have found the DIV and the Element that you highlighted in your screen capture.
WebElement targetElementDiv = null;
WebElement targetElement = null;
targetElementDiv = driver.findElement(By.cssSelector("[class='ui-selectmenu-menu ui-selectmenu-open']"));
if (targetElementDiv != null) {
targetElement = targetElementDiv.findElement(By.cssSelector("[class='ui-menu-item ui-state-focus'])");
}

Related

How to make xPath for ul li a href tags

I am working on this project were I need to verify that each item in list is loaded on page. However I am a bit confused how to create the xpath as the text is inside an tag.
I first need need get the element and then assert if that item is displayed. The below first line works however assertion gives an error.
WebElement costRequest = driver.findElement(By.xpath("//a[contains(text(),'Cost')]"));
Assert.assertEquals(true, costRequest.isDisplayed());
log.info("Verify cost request");
You should use expected conditions - wait for the element to be visible instead of what you are doing now since driver.findElement returns the web element at the moment the element exists, but still not completed so it's not yet displayed.
So do something like this:
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(text(),'Cost')]")));
WebElement costRequest = driver.findElement(By.xpath("//a[contains(text(),'Cost')]"));
Assert.assertEquals(true, costRequest.isDisplayed());
log.info("Verify cost request");

Selenium: How to assert that image is displayed under a certain section of a webpage

I am attempting to write a test that is able to do the following:
1. Navigate to a website.
2. Navigate to a page under the menu.
3. Once in that page, assert that the image I want is displayed under a section labeled "SECTION".
Here is my code (approach 1):
public void test1() throws Exception {
WebElement compare_image = driver.findElement(By.linkText("URL link where the image is located"));
driver.get("website URL");
WebElement image = driver.findElement(By.cssSelector("cssSelector for image from FireFox -> inspect element -> copy CSS selector"));
assertEquals(image, compare_image); }
I am very new to Selenium and QA automation, so any detailed help would be appreciated as my google searches so far are coming up short. It is giving me an element not present exception for the findElement call, but I don't know why as I tried all the Bys I could get from inspect element.
Am I approaching this correctly? If not, what can I do differently?
If you want to check image is present or not under a section then you have to create a webelement for that section.
WebElement section= driver.findElement(By.xpath("//img(#class=‘Section')"));
Now create an image element under section element.
WebElement image= section.findElement(By.xpath("//img(#class=‘Test Image')"));
Now check image is exist or not.
boolean imagePresent = image.isDisplayed();
Now assert on boolean result.
assertTrue(imagePresent, “No image is exist”);
Note: Please take care of locators for section and Image as you didn’t provide Html for it. Code will work perfectly.

Protractor Automation: Selection of element

I'm trying to automate selection of some products...Here's a screenshot
The user clicks on the top row of 'base' colours and then selects the desired colour from the resulting pallet beneath.
I am able to select a base colour without issue.
element(by.xpath('html/body/main-app/kf-sidebar-app/div[1]/app-container/div/dashboard/div/div/visualise/open-interface/div/div/div[2]/div[2]/digitalbridge-category-list/div/digitalbridge-category-view[2]/div/div[1]/div/div[2]')).click();
...selecting the desired colour is altogether much more maddening!!! The closest I've got has resulted in a "Element not visible" message....tried adding in 'waits' but no difference.
This code..
var EC = protractor.ExpectedConditions;
var paintSelected = element(by.xpath('.//div[#id="2386"]'));
browser.wait(EC.visibilityOf(paintSelected), 7000);
paintSelected.click();
..produces line-after-line of..
[11:27:22] W/element - more than one element found for locator By(xpath, .//div[#id="2386"]) - the first result will be used
This keeps running until the 7000ms timeout is reached. I've tried using 'first' but it's not 'recognised'....also tried [0] but again, not recognised.
Here's the line from Console...
<div _ngcontent-c63="" class="item circle" id="2386" style="background-image: url("https://shortbite.s3-eu-west-1.amazonaws.com:443/category/raw/941027c0-f6e6-434c-9ab9-66f9918c33e6.png?Signature=Zbffcvf73Nv9g2v9G3SmcYn6h24%3D&Expires=1510141234&AWSAccessKeyId=AKIAIUUATNKB37DELIXQ");"> </div>
Please try and save my sanity! Thanks
David
Try putting your selector into the console i.e $x(".//div[#id='2386']").
Just to see if you really have two elements with the same Id
Also do a find elements and debug the collection of elements.
One thing I have done with my extended framework is implemented a highlight element functionality.
IJavaScriptExecutor js = Driver as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2])", ReferenceElement, "style",
"border: 2px solid red; border-style: dashed;");
if you have id you can check all elements available with that id in chrome or firefox console like that:
$$('#2386')
$$ will return all, one $ will return the first one.
because if you have more than 1 element with the same locator, protractor will get the first one.
If there is no way to give you elements different locators you can get it by index.
for example in you code first loacte all elements and assign it to varible:
var allColors = $$('#2386'); // same as element.all(by.id('2386'))
or get them by index
var firstColor = $$('#2386').get(0); // or $$('#2386').first();
var secondColor = $$('#2386').get(1); // or $$('#2386').first();
Use firepath and find out the absolute xpath .
Then add some wait and try to click on the element using absolute xpath

click only visible element selenium webdriverjs

I have multiple div like below
<div class="one">send Message</div>
<div class="one">send Message</div>
<div class="one">send Message</div>
I have a web page where there is send Message buttons like above, in which only one button is visible at a time.Other two buttons are hidden via some javascript codes.So for example if 2nd button is visible , I should be able to click only that element.But in my selenium code , its trying to click first hidden div and its failing
driver.findElements(by.className(".one")).then((els) => {
var element = els[index];
element.click();
});
So basically I wanna convert below javascript code to Selenium nodejs code,If some one guide me that will be helpful
var all = document.getElementsByTagName("*");
for (var i = 0, max = all.length; i < max; i++) {
if (isHidden(all[i]))
// hidden
else
// visible
}
function isHidden(el) {
var style = window.getComputedStyle(el);
return ((style.display === 'none') || (style.visibility === 'hidden'))
}
Do you want to click the button ( basically a div as far as code is concerned ) which is visible ?
If that is your main agenda, then the code you've written will fail to find desired element. As you are selecting the element by it's classname not its visibility.
Your code will find all the matched class element. As it's a basic element selector and all your buttons have the same class, so they are basically rendered on the page.
Approach 1
driver.findElements(by.className(".one")).then((els) => {
for(var key in els){
var element = els[key];
if(element.isDisplayed()){ //if visible element
element.click();
}
}
});
The Key here is to check if the element you are trying to click is visible on the page.
Approach 2
By giving a unique class to the target button. Some class for eg 'clickable' or 'active'. So it will be a more optimized solution to select the target element using the Css selector. The Key here is to give uniqueness to your target element to be more identifiable.
Usually many Java Scripts are run in the node Js without the convert.
Have you try it in the node Js without converting ???
** Remember to import selenium

Unable to drag and drop element from 1 div to another div element

I have been trying to drag an element from one div (below)
<article class="media-gallery-item mg-html5">
<div class="mg-thumbnail" draggable="true" data-popcorn-plugin-type="sequencer" data-butter-draggable-type="plugin" data-butter-popcorn-options="{"source":"some_url","thumbnail":"some_url","start":0,"end":10,"from":0,"title":"bdgxkvtbs1.mp4","duration":2.83,"hidden":false,"asset_id":"1457","asset_width":"1280","asset_height":"720","asset_name":"video1.MOV","soundeffects":0}" >
<img src="some_url">
into another div
<div class="butter-track" data-butter-track-id="1"></div>
for dropping onto the element we need can also use pixel values.
I have tried the below code but it didn't drag the element into the div. I could even not see it dragging the element at run time.
WebElement src = driver.findElementBy(By.xpath(".//div[#class='mg-thumbnail']"));
WebElement dest = driver.findElementBy(By.xpath(".//div[#class='butter-track']"));
Actions act = new Action();
act.clickAndHold(src).moveByoffset(src, 0,300).release().build().perform();
I also tried using:
act.clickAndHold(src).dragAndDrop(src, dest).build().perform();
But none dropped the element. (i also could not see the dragging of the element at runtime)
NOTE- the code works for drag and drop as i used earlier but here I'm dragging the element from 1 div to another div so this might be creating the issue.
#pranky301 : Here is the Slight modification in you code.
Please try this and let me know what happens
WebElement src = driver.findElementBy(By.xpath(".//div[#class='mg-thumbnail']"));
WebElement dest = driver.findElementBy(By.xpath(".//div[#class='butter-track']"));
Actions builder = new Actions(driver);
Action drag = builder.clickAndHold(Src).moveToElement(dest).release(dest).build( );
drag.perform( );
These two methods have previously worked for me when dragging and dropping items from one element to another:
WebElement src = driver.findElement(...);
WebElement dest = driver.findElement(...);
new Actions(driver).dragAndDrop(src, dest).build().perform();
or by coordinates:
new Actions(driver).dragAndDropBy(src, "xOffset", "yOffset").build().perform();