Drag and drop automation using Selenide - selenium

There is a ul element with few number of li elements. Also there is a another ul which is empty and need to drag some li elements from first ul into the second ul.
I am using Selenide and I used several methods that I found on the web.
SelenideElement drgthis = $x("//[#id=\"workspace\"]/div[1]/div[2]/div/div/div/div[2]/ul[1]/li[4]");
SelenideElement dragTo = $x("//*[#id=\"workspace\"]/div[1]/div[2]/div/div/div/div[2]/ul[2]");
drgthis .dragAndDropTo(dragTo);
This seems not working but the test is passed. Are there any specific way to do this, please? Is that possible to use Javascript? I tried it but didn't work smoothly.

Related

Materialize select element will not show passed options (empty ul)

My question is probably really easy. I want to populate a Materialize select element with a few options. I don't want to put my options in the HTML, I want to do it from a JSON with javascript (I get the json from a different service). In my HTML file, I just have an empty select.
In the documentation, I see that during the select initalization, you can pass an options object. I assume this can be used to populate the select dropdown. A bit lower it is stated that the correct key is dropdownOptions, and you are supposed to pass an UL to it. I did so, but the UL is empty. Console log shows that the ul is built correctly. What am I missing?
let ul = document.createElement("ul");
arr.forEach(oddelek => {
let li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
ul.appendChild(li);
});
console.log(ul); // looks good
M.FormSelect.init(selects, {
"dropdownOptions": ul
});
What could be the reason that only an empty ul appears?
Because the above code didn't work, I decided to just add the elements to the HTML with javascript, and then run the init with an empty options object. But it doesn't work, the dropdown is still empty.
The init with empty options object works perfectly if the items are added manually in the html, but does not work if they are added through javascript. I have no idea why, I call the init after I add the elements. Inspecting the resulting html without the init looks just like in the documentation. Any advice?

How to read ol and li elements dynamically without using xpath

I'm new to selenium and Below is my HTML and i want to display sons of Dhritrashtra and grandsons of pandu (without using xpath). I've tried methods like getText and getLinkText but it's not working for me. Please help.Thanks.
Kuru
Shantanu
Vichitravirya
Dhritrashtra
DuryodhanaDushasanaDussalanJalagandhaSamaSahaVindhaAnuvindhaDurmukhaChitrasenaDurdarshaDurmarshaDussahaDurmadaVikarnaDushkarnaDurdharaVivinsatiDurmarshanaDurvishahaDurvimochanaDushpradharshaDurjayaJaitraBhurivalaRaviJayatsenaSujataSrutavanSrutantaJayatChitraUpachitraCharuchitraChitrakshaSarasanaChitrayudhaChitravarmanSuvarmaSudarsanaDhanurgrahaVivitsuSubaahuNandaUpanandaKrathaVatavegaNishaginKavashinPaasiVikataSomaSuvarchasasDhanurdharaAyobaahuMahabaahuChithraamgaChithrakundalaBheemarathaBheemavegaBheemabelaUgraayudhaKundhaadharaVrindaarakaDridhavarmaDridhakshathraDridhasandhaJaraasandhaSathyasandhaSadaasuvaakUgrasravasUgrasenaSenaanyAparaajithaKundhasaaiDridhahasthaSuhasthaSuvarchaAadithyakethuUgrasaaiKavachyKradhanaKundhyBheemavikraAlolupaAbhayaDhridhakarmaavuDhridharathaasrayaAnaadhrushyaKundhabhedyViraavyChithrakundalaPradhamaAmapramaadhyDeerkharomaSuveeryavaanDheerkhabaahuKaanchanadhwajaKundhaasyVirajas
Pandu
Yudhishtir
Prativindhya
Bhim
Sutasoma
Ghatotkch
Arjun
Srutakirti
Babhruvahan
Nakul
Satanika
Sahadev
Shrutkarma
Here is the solution for your query:
It's not mandatory to use xpath always. As per the Selenium Documentation & standards, consider the following attributes in sequence: id, name, css, linktext, xpath. If still unable to detect the element try for css/xpath with multiple attributes like class, src, etc.
Once you can identify the element then only you will be able to retrieve the properties of the element like getText() & getLinkText().
Most important, you have provided the copy of the text from the website. It's impossible to identify an an element from the website text to help you out. You need to provide some relevant part of the HTML DOM inorder to enable us to help you. You can look into the PageSource of any webpage to know the properties (id/name/css/xpath) of the elements. For that, while you are on a webpage, you can right-click and select "View Page Source". For Mozilla Firefox you can download & install extensions ​like Firepath & Firebug to know the properties of an element.
Finally you have to write some code either in Java/Python/C# to open a browser through Selenium of your choice, open a website and perform certain actions with different elements present on the webpage.
Let me know if this answers your question.
I don't know the exact syntax your html has but You can use cssSelector as below per my assumptions of your html elements for both your queries:
1) ul ol ol ol li:nth-child(n) - n= element index
2) ul ol ol ol:nth-child(2) li:nth-child(n) li:nth-child(1) - n= element index

webdriver (c#) - Assert text from a specific UL tagname

I'm trying to assert that specific UL tags within my webpage contain certain text. I'm not sure how to get for example, the third UL tag within a class and then assert it's text. Here is an example of the HTML code from my webpage:
<td class="def"><ul>
<li>1 -- test 1</li>
<li>2 -- test 2</li>
<li>3 -- test 3</li>
<li>4 -- test four</li>
</ul></td>
I'm taking a different (and likely naive) approach to get this working but it's not really ideal for me - and I'm only doing it this way because I'm not sure how to get it working the way I would like. I'm asserting that the length of text from the outer html of the "def" class contains a specific count:
(from memory)
String Def = utility.driver.findelement(By.ClassName("def").GetAttribute.("outerHTML");
int Length = Def.Length;
Assert.IsTrue(Length.equals("36"));
You can either directly find that element using an XPath selector that matches on text (example selector below, not tested):
//td[contains(#class, 'def')]//ul/li[text()='4 -- test four')]
(find me a td that contains a class of def, get the ul underneath it, and get the li underneath that which also has a text of 4 -- test four)
You can also harness the power of LINQ in C# to do some leg work for you. The thing you are missing is finding child elements of a given element. This is done by chaining .FindElement commands:
Driver.FindElement(By.ClassName("def")).FindElement(By.TagName("ul"));
The above would get the first ul element that is a direct child of the td element in your example. WebDriver will be able to figure out the child & parent relationships for you.
So to put this into your situation a bit better, here's how you would do it.
Driver.FindElement(By.ClassName("def"));
Get the table we want.
Driver.FindElement(By.ClassName("def")).FindElement(By.TagName("ul"));
Get the ul we want that's a direct child of that table.
Driver.FindElement(By.ClassName("def")).FindElement(By.TagName("ul")).FindElements(By.TagName("li"));
Get the li elements of that ul. Note the FindElements (extra s!)
Driver.FindElement(By.ClassName("def")).FindElement(By.TagName("ul")).FindElements(By.TagName("li")).First(i => i.Text.Equals("4 -- test four"));
Since it's an IList that returns, LINQ can then take it and return the first one that has a .Text property equal to what you need.

How to identify and switch to the frame in selenium webdriver when frame does not have id

Can anyone tell me how I can identify and switch to the iframe which has only a title?
<iframe frameborder="0" style="border: 0px none; width: 100%; height: 356px; min-width: 0px; min-height: 0px; overflow: auto;" dojoattachpoint="frame" title="Fill Quote" src="https://tssstrpms501.corp.trelleborg.com:12001/teamworks/process.lsw?zWorkflowState=1&zTaskId=4581&zResetContext=true&coachDebugTrace=none">
I have tried by below code but it is not working
driver.switchTo().frame(driver.findElement(By.tagName("iframe")));
driver.switchTo().frame() has multiple overloads.
driver.switchTo().frame(name_or_id)
Here your iframe doesn't have id or name, so not for you.
driver.switchTo().frame(index)
This is the last option to choose, because using index is not stable enough as you could imagine. If this is your only iframe in the page, try driver.switchTo().frame(0)
driver.switchTo().frame(iframe_element)
The most common one. You locate your iframe like other elements, then pass it into the method.
Here locating it by title attributes seems to be the best.
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));
// driver.switchTo().frame(driver.findElement(By.xpath(".//iframe[#title='Fill Quote']")));
you can use cssSelector,
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));
You also can use src to switch to frame, here is what you can use:
driver.switchTo().frame(driver.findElement(By.xpath(".//iframe[#src='https://tssstrpms501.corp.trelleborg.com:12001/teamworks/process.lsw?zWorkflowState=1&zTaskId=4581&zResetContext=true&coachDebugTrace=none']")));
Make sure you switch to default content before switching to frame:
driver.switchTo().defaultContent();
driver.switchTo().frame(x);
x can be the frame number or you can do a driver.findlement and use any of the options you have available eg: driver.findElementByName("Name").
1) goto html view
2) type iframe and find your required frame and count the value and switch to it using
oASelFW.driver.switchTo().frame(2);
if it is first frame then use oASelFW.driver.switchTo().frame(0);
if it is second frame then use oASelFW.driver.switchTo().frame(1); respectively
You can use Css Selector or Xpath:
Approach 1 : CSS Selector
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));
Approach 2 : Xpath
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[#title='Fill Quote']")));
https://seleniumatfingertips.wordpress.com/2016/07/05/handling-frames-in-selenium-webdriver-with-java/
Easiest way of doing this is like this. If its a frame you can right click on the field and if you see the choice of "open frame in a tab" do it.
Then take the URL of the frame and that is what you put in your Python script using "driver.get (http://blah blah..)
Then Selenium can find your named element. This saved me hours of trying all the suggestions here which was learning about but didn't work. Problem with mine was it was in a frame.
I'm using Linux which gives me the right-click option of opening the frame, on its own, in another tab. I don't use Windows so don't know if you would get that option in you right-click menu.
Ganzarola
I struggled with this for a while; a particularly frustrating website had several nested frames throughout the site. I couldn't find any way to identify the frames- no name, id, xpath, css selector- nothing.
Eventually I realised that frames are numbered with the top level being frame(0) the second frame(1) etc.
As I still didn't know which frame the element I needed was sitting in, I wrote a for loop to start from 0 and cycle to 50 continually moving to the next frame and attempting to access my required element; if it failed I got it to print a message and continue.
Spent too much time on this problem for such a simple solution -_-
driver.switch_to.default_content()
for x in range(50):
try:
driver.switch_to.frame(x)
driver.find_element_by_xpath("//*[#id='23']").click()
driver.find_element_by_xpath("/html/body/form/table/tbody/tr[1]/td/ul/li[49]/a").click()
except:
print("It's not: ", x)
continue
There are three ways to switch to the frame
1)Can use id
2)Can use name of the frame
3)Can use WebElement of the frame
2->driver.switchTo().frame("name of the frame");
I think I can add something here.
Situation I faced
I cannot or not easily use the debug tools or inspection tools like firebug to see which frame I am currently at and want to go to.
The XPATH/CSS selector etc. that the inspection tool told me doesn't work since the current frame is not the target one. e.g. I need to first switch to a sub-frame to be able to access/locate the element from XPATH or any other reference.
In short, the find_element() or find_elements() method doesn't apply in my case.
Wait Wait! not exactly
unless we use some fazzy search method.
use find_elements() with contains(#id,"frame") to filter out the potential frames.
e.g.
driver.find_elements(By.XPATH,'//*[contains(#id,"frame")]')
Then use switchTo() to switch to that frame and hopefully the underlying XPATH for your target element can be accessed this time.
If you're similar unlucky like me, iteration might need to be done for the found frames and even iterate deeper in more layers.
e.g.
This is the piece I use.
try:
elf1 = mydriver.find_elements(By.XPATH,'//*[contains(#id,"rame")]')
mydriver.switch_to_frame(elf1[1])
elf2 = mydriver.find_elements(By.XPATH,'//*[contains(#id,"rame")]')
mydriver.switch_to_frame(elf2[2])
len(mydriver.page_source) ## size of source tell whether I am in the right frame
I try out different switch_to_frame(elf1[x])/switch_to_frame(elf2[x]) combinations and finally found the wanted element by the XPATH I found from the inspection tool in browser.
try:
element = WebDriverWait(mydriver, 10).until(
EC.presence_of_element_located((By.XPATH, '//*[#id="C4_W16_V17_ZSRV-HOME"]'))
)
#Click the link
element.click()
I could solve that with the following code
browser.switch_to.frame(browser.find_element_by_tag_name('iframe'))

getAttribute not returning complete value for style in selenium

I am using the selenium getAttribute("style") method on the following id element:-
<div id="ntsDiv_1" style="width: 250px; text-align: left; white-space: normal; top: 1090px; left: 131px; visibility: hidden;" class="mlt-pop-container">
but the API is returning only the half of the value. It is returning width: 250px; text-align: left; white-space: normal; and the remaning portion of the style is clipped.
I'm trying to extract the value of the visibility, but the method is not returning the complete value of style. Hence, i am unable to determine the correct value of visibility.
I executed System.out.println("Style is:- "+super.getElement(NEXTAG_STORES_DIV).getAttribute("style"));
NEXTAG_STORES_DIV corresponds to the xpath of the id element, and super.getElement extracts element by xpath
Please help me out!!
I just tried this with Selenium 2.30.0 and it works fine, the whole attribute is returned.
Try the following things (all the examples assume element is the WebElement you need to test):
Make really sure only a part of the attribute is returned. Aren't you just printing it into console? Many consoles have a limited line length. Try setting your console to show long lines. Check programatically the length of the returned value, or try evaluating
element.getAttribute("style").contains("visibility")
Try upgrading your Selenium library, if you can. I am not aware of any bug related to attribute getting, but there might have been some which is now (with version 2.30.0) solved.
Try it in a different browser / OS / architecture. If it works somewhere, you'll know it's an issue of a particular browser / driver / OS / architecture / whatever and you might be able to focus it down and either fix it or file a bug.
If you simply want to know whether an element is visible or not, the correct and generally preferred way is to call
element.isDisplayed()
This method takes care of all the rules you might need to inspect in order to determine whether it actually is visible or not.
If the style value changes dynamically on the page (i.e. it's not statically written in the source code of the page), WebDriver can't really see it as it doesn't pick up dynamic changes. Try accessing the value via JavaScript:
if (!driver instanceof JavascriptExecutor) {
throw new IllegalStateException("JavaScript not enabled for this driver!");
}
JavascriptExecutor js = (JavascriptExecutor)driver;
String styleAttribute = (String)js.executeScript("return arguments[0].style", element);
If you actually need to get the computed value of the CSS visibility attribute that is actually used by the browser and not the one in the style atribute (if there either isn't any or is somehow overridden), you need to use the JavaScript's getComputedStyle() method. One way (described by this article on quirksmode.org) is this:
var elem = arguments[0];
if (elem.currentStyle) {
var vis = elem.currentStyle['visibility'];
} else {
var vis = document.defaultView.getComputedStyle(elem, null).getPropertyValue('visibility');
}
return vis;
Again, this should be invoked via
String visibility = (String)js.executeScript(here_goes_the_whole_script, element);