如何使用 c# 在 Selenium 中单击超链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9441717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to click on a hyperlink in Selenium using c#
提问by Naji Shaban
I am just starting on Selenium. I am trying to invoke click actions upon links on a web page, but for some reason, selenium.click() event is not even showing on the intellisense! inside the foreach loop. Below is partial code of what I am trying to do.
我刚刚开始使用硒。我试图对网页上的链接调用点击操作,但由于某种原因,selenium.click() 事件甚至没有显示在智能感知上!在 foreach 循环内。下面是我正在尝试做的部分代码。
IWebDriver driver;
driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("http://www.google.com");
List<IWebElement> links = new List<IWebElement>();
links= driver.FindElements(By.TagName("a")).ToList();
//driver.FindElement(By.LinkText("YouTube")).Click();
foreach (var link in links)
{
OpenQA.Selenium....;
..
}
Please note that the click works fine in the commented line above the foreach loop. Am I missing a reference?
请注意,单击在 foreach 循环上方的注释行中工作正常。我缺少参考吗?
回答by ctekk
I guess the Bymethod is not finding your TagName. Try the By.LinkText("a")instead:
我猜该By方法没有找到您的 TagName。尝试By.LinkText("a")改为:
links= driver.FindElements(By.LinkText("a")).ToList();
Or try other Bymethods (id,className,...)
或者尝试其他By方法(id,className,...)
:
:
List<IWebElement> links = new List<IWebElement>();
links.add(driver.FindElements(By.TagName("a")));
//driver.FindElement(By.LinkText("YouTube")).Click();
links.get(0).click();
回答by Yi Zeng
Why do you expect selenium.Click();to show up? From the code you provided, looks like you are using WebDriver, not Selenium RC or WebDriverBackSelenium. You probably should consider using something like link.Click();.
你为什么期待selenium.Click();出现?从您提供的代码看来,您使用的是 WebDriver,而不是 Selenium RC 或 WebDriverBackSelenium。您可能应该考虑使用类似link.Click();.
Here is what I do using WebDriver, which works fine for me.
这是我使用 WebDriver 所做的,这对我来说很好用。
IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("http://www.google.com");
// find directly, note it's not in the <a> but in <span>
// driver.FindElement(By.XPath("//span[text()='YouTube']")).Click();
// your logic with LINQ
IList<IWebElement> links = driver.FindElements(By.TagName("a"));
links.First(element => element.Text == "YouTube").Click();
// your logic with traditional foreach loop
foreach (var link in links) {
if (link.Text == "YouTube") {
link.Click();
break;
}
}
driver.Quit();
回答by user2029530
Can you try casting he link to IWebELement in your foreach loop like:
您可以尝试在您的 foreach 循环中将他的链接转换为 IWebELement,例如:
foreach(IWebELelent link in links)
{
------
-----
}
回答by Madhu
driver.FindElement(By.Xpath("")).Click();
or
或者
driver.FindElement(By.Xpath("")).SendKeys(Open.QA.Selenium.Keys.Enter);
Either way is possible
无论哪种方式都是可能的

