Search code examples
seleniumhref

Finding all "A" tags with specific strings in the attribute href?


            driver.FindElement(By.Name("zipcode")).Clear();
            driver.FindElement(By.Name("zipcode")).SendKeys(zipcode);
            driver.FindElement(By.Name("Go")).Click();

            driver.FindElements(By.TagName("A").  //<---- ?????????

I have some Selenium API code that I started. I aim to get all the "A" tags with the string "alertsepy" and the sting "sevendwarves" in the attribute href and return all those elements into an array so I can do some further processing. I started the code but I am really not quite sure how to get all the way there yet. Does anyone know how to do this type of query with Selenium.

Kind Regards!


Solution

  • You should use css selector:

    IList<IWebElement> elements = driver.findElements(By.cssSelector("a[href*=alertsepy],a[href*=sevendwarves]")
    

    This query will return a nodes with href attribute that contains alertsepy or sevendwarves or both strings:

    <a href="alertsepy.html" > </a>
    <a href="sevendwarves.html" > </a>
    <a href="http://sevendwarves.org/alertsepy.html" > </a>
    

    Or you can use:

    IList<IWebElement> elements = driver.findElements(By.cssSelector("a[href*=alertsepy][href*=sevendwarves]")    
    

    This query will return a nodes with href attribute that contains alertsepy and sevendwarves strings:

    <a href="http://sevendwarves.org/alertsepy.html" > </a>
    

    For a list of generally available css selectors refer to w3c css selectors. For the list of available in Selenium query types refer to Locating UI Elements.