Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get attribute value using selenium and css

I have the following HTML code:

<a href="/search/?p=2&q=move&mt=1"> 2 </a>

I would like to get what is contained in href, ie, I was looking for a command which would give me "/search/?p=2&q=move&mt=1" value for href.

Could someone please help me with the respective command and css locator in selenium, for the above query?

if I have something like:

<a href="/search/?p=2&q=move&mt=1"> 2 </a> 
<a href="/search/?p=2&q=move&mt=2"> 3 </a> 

Out of these two if I was to get the attribute value for href whose text conatins '2', then how would my css locator synatx look like?

like image 258
Sunny Avatar asked Aug 26 '11 07:08

Sunny


People also ask

How do you fetch an attribute value of an element in Selenium?

The getAttribute() method fetches the text contained by an attribute in an HTML document. It returns the value of the HTML element's attribute as a string. If a value is not set for an attribute, it will return a NULL value. For attributes with Boolean values, getAttribute() will return either "True" or NULL.

How do I retrieve CSS properties in Selenium?

The values of the css properties can be retrieved using a get() method.

How do you reference an attribute in CSS?

CSS [attribute^="value"] Selector The [attribute^="value"] selector is used to select elements with the specified attribute, whose value starts with the specified value. The following example selects all elements with a class attribute value that starts with "top": Note: The value does not have to be a whole word!

Which method is used to get the attribute value using Selenium Webdriver?

As the name suggests, the getAttribute method gets the value of a given HTML attribute. On the other hand, getText() returns the inner text of a given element.


1 Answers

If your HTML consists solely of that one <a> tag, then this should do it:

String href = selenium.getAttribute("css=a@href");

You use the DefaultSelenium#getAttribute() method and pass in a CSS locator, an @ symbol, and the name of the attribute you want to fetch. In this case, you select the a and get its @href.

In response to your comment/edit:

  1. The part after @ tells Selenium that that part is the name of the attribute.

  2. You should place :contains('2') before @href because it's part of the locator, not the attribute. So, like this:

    selenium.getAttribute("css=a:contains('2')@href");
    
like image 148
BoltClock Avatar answered Nov 12 '22 12:11

BoltClock