how to identify an object with the same name with name property - selenium

I want to find out an object with same name with different value? Here i am interested to identify based on the name only. Do we have index like property provided in QTP. In QTP, if two buttons with same can be distinguished by index, first button with index 0 and second button with 1.
Is there way to do the same in WebDriver?
I want to identify object with name meaning "By.name". How can i do that?
Thanks,
Uday

There are multiple options to achieve it (examples in java):
using findElements and get the appropriate element from the list of resulting web elements:
List<WebElement> elements = driver.findElements(By.name("test"));
WebElement element = elements.get(0);
use xpath based approach (indexing starts from 1 here):
WebElement element = driver.findElement(By.xpath('//input[#name="test"][1]'));

You can also use jQuery style syntax in your search..
For example in Chrome tools $('css selector')[0] will get you the first occurrence of some element.
Selenium comes with a JavaScript driver so you could instantiate that and use that against your site to leverage jQuery.

Related

How to select one from duplicate tag in page in java in selenium webdriver

I am using Selenium WebDriver and I have number of items on a page and each item on page is a separate form type.
I have saved all of these form elements in a list and I am iterating over every item in an attempt to get the name of the element by using the "alt" attribute.
However when I try to get the "name" attribute from the input element it is always returning the first input tag found on that page, not the name attribute of the element I have currently selected.
The syntax I am using is:
((Webdriver imgtags.get(i)).findelement(By.xpath("//input[#name='qty']")).sendKeys ("100");
I have also tried to get the id from the tag by using:
((Webdriver imgtags.get(i)).getAttribute("id");
It's returning a blank value, but it should return the value of the id attribute in that input tag.
I also tried to get the id by using .bytagname but as id is an attribute it is not accessible
Try:
(driver) findElement(By.xpath("//*[contains(local-name(), 'input') and contains(#name, 'qty')]")).sendKeys("100");
To answer the comment by #rrd: to be honest, I have no idea why OP uses ((Webdriver imgtags.get(i)). I don't know what that is. Normally, I just use driver.findElement[...]
Hoping that he knows what works in his framework :D
Selenium Xpath handling is not fully compliant and it does not always treat // as a synonym of descendant-or-self.
Instead try tweaking your code to use the following Xpath:
((Webdriver imgtags.get(i)).findElement(By.xpath("./descendant-or-self::input[#name='qty']")).sendKeys("100");
This will base your search off the currently selected WebElement and then look for any descendants that have a name attribute with a value of "qty".
I would also suggest storing your imgtags array as an array of WebElement e.g.
List<WebElement> imgtags = new ArrayList<>();
This is a much better idea than casting to WebDriver to be able to use .findElement(). This will cause you problems at some point in the future.

Not able to locate webelement

I am not able locate a webelement, this web application opens in Internet explorer only and I have used all the possible ways to click but no luck.
Xpath locators that I have tried :
"//form[#id='Form1']//a[contains(text(),'Age Range')]"
and
"//form[#id='Form1']//a[#id='rptTables1_ctl07_hlTablename1']"
also I have tried click on the element using action class and javascript as well.
Attached DOM in the URL, please have a look here
In the node a, id value is not static so you can't locate that element using the id value but you can use partial id value for example, looks like rptTables1_ is unique in id value and the remaining part is changing so applying contains() on this may works.
Try the below xpath if there is only match :
//a[contains(#id, 'rptTables1_')]
Try the below xpath by providing the matching index if there are multiple xpath matches :
(//a[contains(#id, 'rptTables1_')])[Matching index number]
for example if the matching index is 3 then you can write like this (//a[contains(#id, 'rptTables1_')])[3].
Or you can use the Advanced Performance Parameters Panel Topics text to identify that element.
//a[contains(text(), 'Advanced Performance Parameters Panel Topics')]
Again if there are multiple matches then try to use indexing method as mentioned above.
Or you can try the below modified your xpaths :
//form[#id='Form1']//a[contains(#id, 'rptTables1_')]
or
(//form[#id='Form1']//a[contains(#id, 'rptTables1_')])[Matching index number]
or
//form[#id='Form1']//a[contains(text(), 'Advanced Performance Parameters Panel Topics')]
I hope it helps...
I haven't tried any automation in IE at all but in firefox, sometimes I encounter those issues and my work around other than the .click() function is send_keys(Keys.RETURN). Also, i'm using time.sleep(x) before clicking or sending keys to make sure the element has been loaded.

Unable to recognize Element with relative xpath or other locator

I am facing an issue where I am unable to locate Element on webpage with any type of locator expect Absolute xpath. Here are details:
URL : https://semantic-ui.com/modules/dropdown.html#selection
Required Element Screen shot:
Manually created Xpath Screen shot( Please note that I am able to recognize Element in web application with manually created xpath but Same xpath is not working in selenium code)
But Same xpath is not working in selenium script.
PLEASE NOTE THAT I AM ABLE TO IDENTIFY SAME OBJECT WITH Absolute xpath
Please help to me to understand reason for this.
Here is code:
public static WebDriver driver;
public static void main(String[] args) {
driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://semantic-ui.com/modules/dropdown.html");
//Selection
driver.findElement(By.xpath("//div[#class='ui selection dropdown upward']")).click();
driver.findElement(By.xpath("//div[#class='menu transition visible']/div[text()='Female']")).click();
System.out.println("Done");
This may be issue with your first x-path. You may try the following code. It may work.
driver.findElement(By.xpath("//div[#class='ui selection dropdown']").click();
driver.findElement(By.xpath("//div[#class='menu transition visible']/div[text()='Male']").click();
You are missing a preceding wildcard in you driver.FindElement XPath.
Instead of driver.findElement(By.xpath("//div..."));, do driver.findElement(By.xpath("//*div..."));.
Currently, what your code is doing is telling the XPath locator to find a first level div (not easily possible, as the first item is almost always the document body), but the wildcard of "*" tells it that it can look for the div at any level.
As an aside, please edit your answer up top with actual code instead of pictures so others with the same problem can find their solution easier.
Longshot:
You are using Chrome to look at the source, but Selenium is using Firefox.
There is a chance that the source is rendered differently between the two browsers. Specifically, your xpath is relying on an exact match of class. I do know that FireFox is notorious for modifying source output.
I haven't done any testing but I would not be surprised if the class is in a different order and it's failing on an exact match.
There are two solutions if that is the case:
Don't do a single exact match (xpath = "") but instead do a mix of contains joined with && (contains ui && contains selection && dropdown)
Don't rely on the output from the console tab. Instead "View Page Source" and view what is actually being sent instead of what is being interpreted by the browser
Find the dropdown container element firstly, then use it to find self descendant, like option etc.
driver.get("https://semantic-ui.com/modules/dropdown.html");
// find dropdown container element
WebElement dropdownWrapper = driver.findElement(
By.xpath("//div[#class='html']/div[input[#name='gender']]"));
// expand drop down options by click on the container element
dropdownWrapper.click();
// or click the down arrow
dropdownWrapper.findElement(By.css('i')).click();
// select option
dropdownWrapper.findElement(By.xpath(".//div[text()='Female']")).click();
To locate the element with text as Gender and select the option Female you can use the following Locator Strategy :
Code Block :
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://semantic-ui.com/modules/dropdown.html#selection");
driver.findElement(By.xpath("//div[#class='another dropdown example']//div[#class='ui dropdown selection']")).click();
driver.findElement(By.xpath("//div[#class='another dropdown example']//div[#class='ui dropdown selection active visible']//div[#class='menu transition visible']//div[#class='item' and contains(.,'Female')]")).click();
System.out.println("Gender Female selected.");
Console Output :
Gender Female selected.
This might be helpful to clearify how selectors are working in general:
.(dot): Dot at starting represents the current node. It tells us that the processing will start from the current node.
. .(double dot): It will select parent of current node. For example, //table/. . will return div element because div is the parent of table element.
‘*’: is used to select all the element nodes descending from the current node. For example:
/table/*: It will select all child elements of a table element.
//*: It will select all elements in the document.
//*[#id = ‘username’]: It will select any element in document which has an attribute named “id” with the specified value “username”.
#: It represents an attribute which selects id, name, className, etc. For example:
#id: It will select all elements that are defined with the id attribute in the document. No matter where it is defined in the document.
//img/#alt: It will select all the img elements that are defined with the #alt attribute.
//td[#*]: It will select all td elements with any attribute.
Here is a link to the article:
https://www.scientecheasy.com/2020/07/selenium-xpath-example.html/

how to select the check box using selenium?

How to select the checkbox which has a dynamically changing ID and XPath?
Multiple ways:
You should look at a pattern like id or name somoething like
CT_CHKBox_157, CT_CHK_158 etc.. For example, to click the first
Checkbox having a pattern of Ids
You can use a dynamic xpath like driver.findelement(By.xpath(//input[starts-with(#id,'CT_CHK'][1]).click()
Identify the Unique Element which are close ancestors to the
Checkbox in question and reach out to it through xpath or css path
relatively or through indexing from within.
Hope that clarifies.
Have you tried XPath by position? Ultimately the check boxes are like buttons or link that can be clicked so driver.findElement(By.xpath("//xpath by position")).click();
Alternativey you might want to use JavaScript:
((JavascriptExecutor) driver).executeScript("return document.getElementsByName('ChkboxValue')[0].checked;");
Hope this helps.
Selenium uses what is called locators to find and match the elements.There are 8 locators strategies included in Selenium:
Identifier
Id
Name
Link
DOM
XPath
CSS
UI-element
you can try using any other Locator in the list.

Selenium nth match by id without common parent

I have to test some complicated web service using Selenium.
Problem is that ids of elements are changing from session to session.
For example there is bunch of inputs each have id with prefix textf_id_DComboBox_ and ends with a consecutive numbers, starting number is random (session dependent).
Those inputs doesn't have a common parent so nth-child doesn't work.\
I can find first input by using selector: css=input[id^='textf_id_DComboBox_'] but I have no idea how to find next items (1-7) which match this selector.
I've found some suggestions on stackoverflow that xpath selector should be used, but I was unable to adopt examples for my use case.
Update:
I have also alternative selector which captures first input: css=td.DForm_treeGridNoWrap input.
You can use this XPath in order to select all inputs that contain a common id:
string comboBoxXPath = "//input[contains(#id, 'textf_id_DComboBox')]";
List<WebElement> comboBoxElements = driver.findElements(By.XPath(comboBoxXPath));
At this point, you can iterate through the entire collection, or you can select which one you'd like to interact with by using an index:
comboBoxElements[1]
comboBoxElements[2]
comboBoxElements[3]
etc...
Well, that descrption does not help that much. You can try these tricks:
You can call findElement on WebElement This trick will probably not work, because those IDs do not have common parent. But if they are wrapped, say, in table, you can find the table first:
WebElement table = driver.findElement(By.id("the-table"));
And then to find all input in such table:
List<WebElement> inputs = table.findElements(By.tagName("input"));
Install Selenium IDE to your firefox and try record testcase by using it. You can play with target in Selenium IDE.
Dirty approach
List<WebElement> allInputs = driver.findElements(By.tagName("input"));
Will find all inputs in such page.
Footnote: The code is Java and driver variable is considered as healthy instance of WebDriver