简体   繁体   中英

How to use Selenium to grab nested LinkText?

I'm using Selenium in C# to click on a link called 'Store Locator'. My current code is as follows but does not click on the link:

IWebElement storeLink = driver.FindElement(By.LinkText("Store Locator"));

Here is the original HTML, notice there is a span element nested in the tag, not sure if this makes a difference.

<a href="/site/olspage.jsp?id=cat12090&amp;type=page&amp;rdct=n" data-lid="hdr_stl"><span class="header-icon-storeFinder" aria-hidden="true"></span>Store Locator</a>

Seems like the link is hidden. If even Selenium finds the link it will not be able to interact directly. In that case JavaScript is your only option

By xpath = By.XPath("//span[contains(text(),'Store Locator')]");
IWebelement element = driver.FindElement(xpath);
((IJavaScriptExecutor)driver).ExecuteScript(@"arguments[0].click();",element);

This will work for sure.

IWebElement storeLink = driver.FindElement(By.LinkText("Store Locator"));
storeLink.click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM