How to print this ajax text in selenium? - selenium

I am trying to automate Snapdeal website.
Steps followed:
SnapdealHome->Hover on Computer&Gaming->Storage->Select 1TB and 16gb both.
Then I want to print what all does the Capacity filter contains.
I tried this xpath but it doesn't show anything.
Is this an ajax code?
I want to print what all does the capacity.getText() contains.
These are the xpaths I tried:
$x("//div[#class='navFiltersPill'][contains(text(),'Capacity:')]") and $x("//div[#class='navFiltersPill']").
Output should be: 1TB and 16GB both. Is it possible?
Check the below attached figure

Please try to use findElements with below xpath and then retrieve the text by looping all matching elements one by one. This will specifically list out all the filtered conditions under Capacity filter section. Change the below data-name value in the xpath according to your requirement.
//div[#data-name='Capacity_s'][contains(#class,'filter-inner filter-inner-height')]/div[contains(#class,'active-filter')]/label/a
Sample code: [Make sure to add wait before hitting this line]
List<WebElement> ele=d.findElements(By.xpath("//div[#data-name='Capacity_s'][contains(#class,'filter-inner filter-inner-height')]/div[contains(#class,'active-filter')]/label/a"));
for (WebElement e:ele){
System.out.println(e.getText());
}

You will have to loop through all the checked INPUTs and print their value. For example,
for (WebElement e : driver.findElements(By.cssSelector("input[checked]")))
{
System.out.println(e.getAttribute("value"));
}
will print
1%20TB
16GB
The %20 is a space.

Related

Not able to click or page not responding to click in phantomjs-selenium in java

I am doing project on different crawlers and trying to mimic user actions. As part of it, I am crawling this url. Here there is a zip code box and I am trying to click on it and extract text from the drop down which will appear after that. I wrote the below code but not sure why it is not working at all. Can anyone please help? I did exhaustive search to find root cause but got nothing. Any suggestions would be much much appreciated.
driver.getUrl(aboveUrl);
WebElement inputBox = driver.findElement(By.id("pincodeInputId"));
inputBox.click();
System.out.println(driver.findElement(By.className("_3mWImx")).getText());
-- This gives null;
Awaiting help !
The reason is the node that you picked is the parent node of the element that has the text
You should use
System.out.println(driver.findElement(By.css("_3mWImx span")).getText());
And that would work. Also note that there are multiple element with the class _3mWImx, so this will only give you the first one. If you are interested in all of them, then you should be using driver.findElements and looping through the result
Actually there are more than one values in the drop down if you want to print all you have to used findElements(). Use this code it will give you desired result :
WebDriver driver=new FirefoxDriver( );
driver.manage().window().maximize();
driver.get("https://www.flipkart.com/moto-e4-plus-fine-gold-32-gb/p/itmevqynuz4fwxca");
WebElement inputBox = driver.findElement(By.id("pincodeInputId"));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
inputBox.click();
List<WebElement> elements=driver.findElements(By.className("_3mWImx"));
for(WebElement ele:elements)
{
System.out.println(ele.getText()); //It will print innertext of each element
}
Output :
From Saved Addresses
Loginto see your saved addresses

How to handle Auto Suggestion feild in app:Urgent

I want to handle the auto suggestion text field in which typing few letters will automatically list the options from which i want to click and select the option. but I'm facing the issue in selecting the option from the list
Any Any Way of handling this ... please help with some suggestion im stuck on this .....
enter image description here
After entering few characters wait until the screen which appears with suggestion using any xpath.
//Assume suggestionlist is your id
driver.findelementbyid("suggestionlist")
One done take all elements in list.
#findby (id="suggestionlist")
List <AndroidElement> list;
once you get the list please manipulate that .
foreach(element in list)
{
if(element.gettext().equals("your desired value"))
element.click();
}

How to store and echo all ID's of present input fields by XPath in Selenium?

I am learning Selenium for automation testing and I am going through and trying to build up some test steps for basic account sign up on a website.
The process will involve grabbing all ID's of input fields within a form and then save those ID's to a variable(s) and echo all of those ID's back.
Currently my XPath looks something like:
//*[contains(concat(' ', normalize-space(#class), ' '), ' textField')]/descendant::input
Which, in Firebug highlights all of the input fields.
Now my question is, how would I go about saving the ID's of those input fields and echoing those back in Selenium for verification/debugging purposes?
I tried getting a better idea from: How to store the content/value of xpath?, but the only thing echo'd and saved in the temp variables is just the name of the variable I gave it.
(We'll call this variable "AllFormInputIDs")
Any and all help is super appreciated and any tips for more efficient XPath mark-up/code mark-up would be great! Thanks :)
You can follow the below process:
Find all the input tag elements in the page and store it in a list.
Iterate through the list, fetch the attribute id using getAttribute() method and store it in another Arraylist, say AllFormInputIDs as you mentioned.
Now you can iterate over the list of "AllFormInputIDs" to do any operation you want.
Below is the Java code snippet for the aforementioned process:
//Opening firefox driver instance, maximizing and assigining an implicit timeout of 20 seconds.
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Navigating to the site
driver.get("http://stackoverflow.com/questions/31574046/how-to-store-and-echo-all-ids-of-present-input-fields-by-xpath-in-selenium");
//Fetching all the elements with tag 'input' and putting in a List
List<WebElement> List_Inputs = driver.findElements(By.tagName("input"));
//Creating an ArrayList object
ArrayList<String> AllFormInputIDs = new ArrayList<String>() ;
//Iterating throught the input ids in List_Inputs and fetching the 'id' attribute
//where 'id' value is not an empty string
for(WebElement inputID: List_Inputs){
if(!inputID.getAttribute("id").equals(""))
AllFormInputIDs.add(inputID.getAttribute("id"));
}
//Iterating over AllFormInputIDs where the fetched id's of all Input tags are present
//and printing them
int i=1;
for(String id: AllFormInputIDs){
System.out.println("ID "+(i++)+": "+id);
}
Once you have found your element(s), you can use getAttribute method to retrieve the attached attribute of the element and store it.
Lets say we want to print all href links which starts with 'Stack' on this page inside footer:-
python code:
for element in driver.find_elements_by_xpath("//*[#id='footer']//../a[contains(.,'Stack')]"):
print(element.get_attribute('href'))
prints:
https://stackoverflow.com/ https://stackapps.com/
https://meta.stackexchange.com/ http://careers.stackoverflow.com/
Printing the id of the Ask Questions Button
print(driver.find_element_by_xpath("//*[text()='Ask Question']").get_attribute('id'))
nav-askquestion
Working example of a Python file for the same: GitHubFile

Locating images uniquely when img ids are dynamic and src same for multiple images

I have 3 custom dropdowns which open when clicked on "down arrow" image appended at the end, Code for the image is something like :
<img id="x-auto-2017" class="x-form-trigger x-form-trigger-arrow "
src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==">
Image id are dynamic and are in order of like 2017, 2018 etc. So I cannot use contains and identify them uniquely.
I want to get them clicked one by one and select value from the dropdown. Please help how to identify them uniquely.
Below code should work for you:
List<WebElement> elements = driver.findElements(By.xpath("//img[contains(#class,'x-form-trigger x-form-trigger-arrow']"));
System.out.println("Number of drop downs on the page: " + elements.size());
for (WebElement ele : elements) {
ele.click();
//Do what ever you want
}
Thanks for your response, I used the position qualifier [N] as suggested by #Marcus, though have to hit and trial a bit but writing manual xpath on Chrome console I got the following answer to my query.
driver.findElement(By.xpath("(//img[starts-with(#id,'x-auto-2')])[2]")).click();

How to find the element within element in selenium

I am creating a framework for the data validation using selenium. The issue I am struggling with is I want to locate the element "td"(html tag) within element "tr"(html tag) . This is the code I have written.
Iterator<WebElement> i = rows.iterator();
While(i.hasnext()){
List<WebElement> columns = row.findElements(By.tagName("td"));
for(WebElement s:columns)
{
System.out.println("columnDetails : "+s.getText().toString());
}
if(columns.isEmpty())
{
ElementNotFoundException e = new ElementNotFoundException("No data in table");
throw e;
}
Iterator<WebElement> j = columns.iterator();// does some other work
ClusterData c = new ClusterData(); // does some other work
ClusterDataInitializer.initUI(c, j, lheaders); // does some other work
CUIData.put(c.getCN(), c); // does some other work
}
Now the issue with this is:
I am trying to fetch the data from the rows(see table data) in arraylist and use that arraylist further. Currently whats happening is the data for column header is fetched at start of which I have no use.I only want the rows's data. I am not able to determine the proper way to collect the data of table rows only.
if xPath of the table will help you understand it properly then here are the details :
Table header xPath of cluster name column:
/html/body/table/tbody/tr[2]/td[2]/div[2]/div/div/div[2]/div/div/div[2]/div/div/div[2]/div/div/div/div/div/div[2]/div/div/div[2]/div/div/div[2]/div[2]/div/table/tbody/tr/td[2]/div/div[2]
Table row (Table Data) xPath of test cluster 01:
/html/body/table/tbody/tr[2]/td[2]/div[2]/div/div/div[2]/div/div/div[2]/div/div/div[2]/div/div/div/div/div/div[2]/div/div/div[2]/div/div/div[3]/div[2]/div/table/tbody/tr/td[2]/div/div/a
Please let me know if you need anything else.
I am using the following code to extract row data from table.
List<WebElement> rows = getElement(driver,sBy,"table_div_id").findElements(By.tagName("tr"));
where sBy = By.id and table_div_id = id of div in which table is present. This extracts all the rows into arraylist and then i am using code to extract the row data into another arraylist. It is where I am stuck.
Each row from the table is in its own "table" tag so following things are not working :-
List<WebElement> rows = driver.findElements(By.xpath("//div[#id = 'table_div_id']//tr"));
List<WebElement> columns = row.findElements(By.xpath("./td"));
or the approach I used for the previous release of product i.e.
List<WebElement> columns = row.findElements(By.tagName("td"));
So, I used following approach which enabled me to capture all of the visible rows from the table.
List<WebElement> columns = row.findElements(By.xpath(".//table[#class='gridxRowTable']/tbody/tr"));
But after that I faced another issue that is since this table was implemented using dojo, the scrolling was impossible and Selenium was only able to capture the visible rows , so to overcome this I zoomed out in the browser using selenium. This is how i achieved my goal of getting the data.I believe others might have provided me answer if i would have shared some more details. Still , sorry about that and hope my answer helps you all.
instead of
List<WebElement> columns = row.findElements(By.tagName("td"));
try using
List<WebElement> columns = row.findElements(By.xpath("./td"));
Check if this helps. This should give you the td elements. If I have not understood your issue, let me know.
You can use this way-
driver.findElement(By.Xpath("//table[#id=\"table1\"]/tbody/tr[2]/td[1]"));
Regards,
Anuja
Do you have selenium IDE installed? Perform storeText operation on the row you want to retrieve, then xpath will get populated in IDE. There will be multiple xpaths; the most reliable is xpath:position, use that to capture your rows.
And use firebug for better visibilty of your AUT.
Firebug and Selenium IDE are the most basic component of Selenium Framework development.
You can manipulate xpath as you want.