I have a project to click through specific links on a web page using Selenium WebDriver with C# and I'm struggling to find a clean way to iterate through them with an array that accounts for specific cases.
I understand how to do basic driver.FindElement(By.XPath(" "));
But I'm not sure how I could create a WebElement Array to feed a foreach statement that would search By.TagName("a") in specific div classes without pulling every link on the page.
Example of what the header of the website looks like:
<header>
<div id="ContainerTopStrip">
<div class="ContainerWidth">
<div class="headerMenu">
<a href="Account/IntakeLogin" title="Report">Report</a>
<a href="/rfs" title="Request">Request</a>
<a href="javascript:void(0);" onclick="openFullWindow();" title="Lookup">Lookup</a>
</div>
</div>
</div>
</header>
Basic example of what I have just using findelement:
using System;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;
class Program
{
static void Main()
{
using (IWebDriver driver = new ChromeDriver("C:\\"))
{
driver.Navigate().GoToUrl("xxx");
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
driver.FindElement(By.XPath("//a[text()=\"xxx\"]")).Click();
// TODO: Figure out how to assert route change occurred
driver.FindElement(By.XPath("//a[text()=\"xxx\"]")).Click();
driver.Navigate().Back();
driver.FindElement(By.XPath("//a[text()=\"xxx/I\")]")).Click();
driver.Navigate().Back();
Console.WriteLine("This is what happens when you don't know how to make an array.");
driver.Quit();
}
}
}
So to summarize:
Need help finding a way to create an array that could find specific links to be clicked in a loop because that seemed like the neatest solution after searching for awhile now. If there is a better suggestion available, I'm open to it. Just completely new to C#/Selenium in general.
You can get all the links by determining the xpath of links
var links = myWebDriver.FindElements(By.XPath("/html/body/div[2]/header/div[1]/div/div/a"));
//loop through all header links
for (int i = 0; i < links.Count; i++)
{
//reassignment because of reloading the page after each navigation
links = myWebDriver.FindElements(By.XPath("/html/body/div[2]/header/div[1]/div/div/a"));
myWebDriver.Navigate().GoToUrl(links[i].GetAttribute("href"));
//or you can click
//links[i].Click();
myWebDriver.Navigate().Back();
}
and for the next links is shown in the picture :
var links2 = myWebDriver.FindElements(By.XPath("/html/body/div[2]/header/div[2]/div/ul/li/a"));
for (int i = 0; i < links2.Count; i++)
{
links2 = myWebDriver.FindElements(By.XPath("/html/body/div[2]/header/div[2]/div/ul/li/a"));
myWebDriver.Navigate().GoToUrl(links2[i].GetAttribute("href"));
//or you can click
//links2[i].Click();
myWebDriver.Navigate().Back();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With