maxrena
maxrena

Reputation: 561

Selenium C#: Get Element by title

I want to get an element by its title, I don't know if we have a universal solution for this in Selenium C#. Here is the example of the HTML

   <div class="student">
     <a href="abcxyz.com">
        <span class="title"> ZZZ</span>
     </a>
   </div>

And another example

   <div class="page">
      <a href="asdf.com" class="button-1" title="ZZZ"> </a>
   </div>

Of course if just one page, I will do it like

   FindElement(By.ClassName("page")).GetAttribute("href");

or

    FindElement(By.ClassName("student")).GetAttribute("href")

to get the "href" out of where the "title" is located. But they have pages with different designs, and the only common thing between them is that title. I wonder if there is any solution for me to find the "href" by the "title=ZZZ"? Thanks in advance.

Upvotes: 1

Views: 1562

Answers (2)

ThePyGuy
ThePyGuy

Reputation: 1035

Try this xpath:

/a[@title="ZZZ"]/@href

Upvotes: 0

K. B.
K. B.

Reputation: 3690

The two examples are different, I would use a union (|) operator of XPath expressions that will work in both cases. If you have more cases, you can add additional union operator, followed by the new case XPath:

//a[@title='ZZZ']/@href | //*[@class='title'][contains(text(),'ZZZ')]/parent::a/@href

Without searching for specific text:

//a[@title]/@href | //*[@class='title']/parent::a/@href

Upvotes: 1

Related Questions