Webdriver click second element in list - selenium

The page I'm testing has 2 elements with the same name and I need to click the second Element.
I can get the elements by using:
driver.findElements(By.linkText("Services"));
But I don't know how to click on the second element.

There are two ways to do this:
1) Using xpath, try in following manner.
driver.findElement(By.xpath("('xpath of the link')[2]"));//If you had given html, I could have added exact xpath.
2) Using findElements() you can try following:
List<WebElement> li = driver.findElements(By.linkText("Services"));;
li.get(1).click();//If there are only two such element, here 1 is index of 2nd element in list returned.
Hope you get the idea. :)

Or for short you can do
driver.FindElements(By.ClassName("drop"))[1].Click();

If you`re using python, you can try this way:
li = driver.findElements(By.linkText("Services"))[index].click()

Related

Click on first element contained in a div

I have a div that contains a set of dynamic elements. I want to click on the first search result.
I want to click on the first element contains in
I tried using creating a custom xPath like so but it didn't work. Any ideas here?
//div[1][contains(text(), 'listing')]
First of all It would've helped if you had provided more information.
best will be using pseudo-child like div.firstChild or if the elements are generated dynamically you can add a class and use document.querySelectorAll(".class") which will give you an array of elements that had the class.
You can use array[0] to use click on the first element.
For anyone coming across this thread here is the solution
const listings = await page.$x('//*[contains(#id,"listing_")]')

How can I check that a dropdown field is disabled using selenium?

I am trying to write a function in selenium to check if a Reasons dropdown is showing as disabled, but can't quite get the xpath right. The code for the dropdown is in the pic, the function I'm working on is the second one (InputDisabled), having based it on the working first one (SearchDisabled):
` public By SearchDisabled(string searchId) => By.XPath($"//div[#id='{searchId}']//div[contains(#class, 'v-input--is-disabled')]");
public By InputDisabled(string inputId) => By.XPath($"//div[#id='{inputId}']//div[contains(#class, 'v-input--is-disabled')]");`
The inputId going into it is 'ai-confirm-allergy-modal-reason'. I've tried it as 'input[contains...' and 'contains(#disabled, 'disabled'...' among other things, but my xpath knowledge isn't great yet!
dropdown code
Use below code
String value = driver.findElement(By.XPath("//input[contains(#id, 'ai-confirm-allergy')]").getAttribute("disabled");
Assert.AssertEquals(value, "disabled");
I do not quite get your question.
well if you are trying to use xpath to locate an element, you can just use the id; assuming that it is unique.so:
driver.findElement(By.xpath("//input[contains(#id, 'ai-confirm-allergy')]")
should locate the webelement.
However, your xpath for the SearchDisabled is locating a div containing class 'v-input--is-disabled' with in another div with id of '{searchId}';
the same logic goes for the next one. your xpath is trying to locate a div containing class 'v-input--is-disabled' which is located with in another div located using input id. I don't think this combination can locate the element highlighted in the picture.

How to locate an element using selenium webdriver which doesn't have unique identifier like Name, Id, title etc?

I am new to Selenium. Not sure how to handle this scenario. I am working on a website which has several buttons with following code,
<a class="Some big class name" datacommunication="SelectItem" token="some token number" model-id="Id1" element="button">
<i class="classname">Book Ticket</i>
</a>
<a class="Some big class name" datacommunication="SelectItem" token="some token number" model-id="Id2" element="button">
<i class="classname">Book Ticket</i>
</a>
I tried to click on it using following commands,
ele = driver.FindElement(By.ClassName("Some big class name")); but it fails with following message, Compound class names are not supported. Consider searching for one class name and filtering the results.
ele = driver.FindElement(By.CssSelector("a[model-id='Id1']")); fails with 'Test method TestBot.HomeTest.bookTicket threw exception:
OpenQA.Selenium.WebDriverTimeoutException: Timed out after 10 seconds'
Tried using XPATH,
ele = driver.FindElement(By.XPath("\\\a[#model-id='Id1']")); doesn't work either.
I have no control on html. Can't change it.
Please let me know how to identify elements in such scenarios.
You can't have spaces in class names. Those are actually multiple classes separated by a space. You can find the above elements using a css selector
var ele = driver.FindElements(By.CssSelector(".Some.big.class.name"))
Of course, this will find both elements. To find just the first, you could use
var ele = driver.FindElement(By.CssSelector("a[model-id='Id1']"))
You can find help on css selectors here: http://www.w3schools.com/cssref/css_selectors.asp
Update:
I just noticed your XPath appears to have the slashes the wrong way around. If you wish to use XPath, try
//a[#model-id='Id1']
Note, however, that css selectors perform better than XPath.
There are multiple number of ways to locate your WebElement in Selenium WebDriver.
But always remember all are based on you attribute or combination of HTML tags so case could be any of them
1- First way is using id
2- 2nd one is Name
3- Class Name
4- Some time you can used Tagname
5- Some time linkText
6- Some time partial link text
7- Using xpath
8- Using css selector
So in you case we need to take help of Xpath and Css Selector
So xpath of you elements
Syntax : //[#attribute ='value of selected tag']
Example
id1: //a[#model-id='Id1']
id2: //a[#model-id='Id2']
For both element following are the css Selector
Syntax [attribute ='value']
id1:
a[model-id='Id1']
id2:
a[model-id='Id2']
http://www.slideshare.net/weekendtesting/css-selector-29312437
http://www.slideshare.net/weekendtesting/locators-in-selenium-bnt-09
Thanks a lot for help. I have used following code to overcome above mentioned issue,
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("a[data-model-id='c5']"))).Click();
With above code, I am able to click on the button.
Thanks again for your help and knowledge sharing.
Amit
You can locate by using xpath.
WebElement ele = driver.findElement(By.xpath("//*[#class='Some big class name']"));
there is difference between findElements and findElement.
FindElement: findElement returns a single element.
FindElements : returns a list of same element.As in this example there are multiple classes with same class name , so use driver.findElements method .
driver.findElements will return a list of all elements with that class name .
Now , you have list of all elements but you want only one of the element.
So iterate over list to get a single element out of a list.
List<WebElement> elementList= driver.FindElement(By.ClassName("Some.big.class.name"));
Iterator itr = elementList.iterator();
while(itr.hasNext())
{
WebElement element = itr.next();
if(element.getAttribute("model-id").equals("Id1")){
element.click();
break;
}//if block ends here
}//while loop ends here
You can also use XPATH , if nothing works
To identify the elements in selenium there are multiple ways.
To see the details please refer BY Class.
Try to find the way which can identify the element uniquely. Start with id if available and if nothing works go for XPATH. XPATH is slower than id and CSS selector.

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.

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

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.