Search code examples
c#seleniumwebdriverarticletagname

Selenium - Discerning Between Identical <articles>, C#


I'm trying to have my program sit on a webpage and wait for specific tagName within an article to appear. Problem is, I need Selenium to check the article contains two tagNames before clicking it, that's where I'm stumped. The way I have my code setup right now, it doesn't click anywhere. It just sits on the page, I suspect because there's more than one article with the same main tagName that I'm trying to find. Here's the HTML:

<article>
   <div class ="inner-article">
      <a href ="/shop/shirts/iycbmgtqw/x9vdawcjg" style="height:150px;">
         <img alt="Xrtqh7ar444" height="150" src="//d17ol771963kd3.cloudfront.net/120885/vi/xrTQH7Ar444.jpg" width="150">
      </a>
      <h1>
        <a href="/shop/shirts/iycbmgtqw/x9vdawcjg" class="name-link">EXAMPLE_CODE</a>
      </h1>
      <p>
        <a href="/shop/shirts/iycbmgtqw/x9vdawcjg" class="name-link">EXAMPLE_COLOUR</a>
      </p>
   </div>
</article>

All other items on this page have an identical class, and some have identical tagNames. I want to search for when there's a specific combination of two tagNames in an article. I realize xPath is an option, but I would like to code it before knowing an xPath, where the name of the item is the only available information.

And here's the code I'm working with at the moment:

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMinutes(10));


IWebElement test = driver.FindElement(By.TagName(textBox12.Text));
test.Click();

where textBox12.Text is "EXAMPLE_CODE". Am I correct in assuming that WebDriver doesn't click anything because there is more than one element with the tagName "EXAMPLE_CODE", and is there a possible way to make it first look for "EXAMPLE_CODE" and then check the secondary: "EXAMPLE_COLOUR"?

Thanks!!


Solution

  • You are using By.TagName incorrectly. Tag refers to the type of element you are trying to find. In this case for the link it is 'a'. Or in case of a div it is 'div'. Te correct way of finding with tagname for a link would be - By.TagName("a").

    You need to match text and you will need to use xpath. Assuming that the code is unique you should try.

    XPath to get the code href -- //div[class='inner-article']/h1/a[.=EXAMPLE_CODE]

    XPath to get the color href -- //div[class='inner-article']/h1/a[.=EXAMPLE_CODE]/following-sibling::a