Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select an element by the text it contains with Selenium Webdriver

I've jjust started off with Selenium Webdriver and I've hit an issuee straight away involving the buttons I'm trying to select/click all have no IDs and share the same class.

So I'm wondering how I select these by the unique text they contain.

I'm thinking possibly with css selector maybe, but I'm unsure how to also tell it to look for specific text to select the element.

All I currently have is:

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium.Internal;

namespace SeleniumTest1.Methods
{
    public class HomePage
    {

        private readonly IWebDriver _browser;
        public HomePage(IWebDriver browser)
        {
            _browser = browser;
        }

        public IWebElement SearchBox()
        {
            return _browser.FindElement(By.Id("searchBox"));
        }

        public void ImageButton()
        {
            _browser.FindElement(By.CssSelector("a")).Click();
        }

    }
}

Very basic so far.

Where I have the CssSelector I'm not sure if theres anyway to say select "a" containing text "xyz".

I've tried search for ways but can't find anything, though I feel this must be an issue which has been raised before, thanks.

like image 405
Vereonix Avatar asked Dec 03 '22 19:12

Vereonix


1 Answers

Fairly easy if you use xpath. if it has unique text your xpath should look like something like this

//button[.='xyz']

So, here "." points to the parent in HTML hierarchy and just look for text

like image 199
Saifur Avatar answered Jan 02 '23 22:01

Saifur