I am new in seleni开发者_运维知识库um testing. I want to get the css class name using selenium. I am using eclipse and Java for development.
<table >
<tr class="odd"><td>Odd row</td></tr>
<tr class="even"><td>Even row</td></tr>
<tr class="odd"><td>Odd row2</td></tr>
<tr class="even"><td>Even row2</td></tr>
</table>
Is there any way to get the class name 'odd' or 'even' using selenium? I
From a WebElement
you can use the getAttribute
method like this:
element.getAttribute("class")
Yes, you can use getAttribute(attributeLocator)
function for the your requirement.
selenium.getAttribute(//xpath@class);
Specify the Xpath of the element for which you require to know the class of.
Thanks.
There is nothing depending on eclipse or java, in fact it is more about location strategy. If you want to access specific tr element with/without css class you can use css locator:
css=tr:nth(indx_base_0)
nth row with class
css=tr.odd:nth(indx_base_0)
first row with class odd
css=tr.odd
Using xpath:
//tr[index_base_1]
first row with class odd
//tr[@class='odd']
nth row with class odd
//tr[@class='odd'][index_base_1]
Here are some useful examples
In context of the code snippet, say you want to get the class "odd" for the first row in the table.
You can follow the below steps:
(Note:- Assuming there is one table in your webpage)
1- Get the element first:
WebElement ele = driver.findElement(By.xpath("//table/tr[1]"));The above code uses the xpath to get the element, i.e., the first row of the table.
2- Then, get the attribute "class" of the element using "getAttribute" method:
String class_name = ele.getAttribute("class");The above code will fetch the "class" name of the related element and assign it to the String variable "class_name" for further use
Similarly, for getting "even" class, which is the attribute for fourth row of table , you can use the below code:
ele = driver.findElement(By.xpath("//table/tr[4]")); class_name = ele.getAttribute("class");
If CSS is your requirement, and in the absence of additional/differentiating element attributes, try the following (in the example, I have used simple text assertions):
assertEquals(selenium.getText("css=tr.odd > td"), "Odd row");
assertEquals(selenium.getText("css=tr.even > td"), "Even row");
assertEquals(selenium.getText("//tr[3]/td"), "Odd row2");
assertEquals(selenium.getText("//tr[4]/td"), "Even row2");
Getting the CSS class name using Selenium using C#:
string _className;
IWebElement _ele = _driver.FindElement(By.Xpath("Xpath of Element"));
_className = _ele.GetAttribute("AttributeName Here");
精彩评论