简体   繁体   English

Selenium - C# - Webdriver - 无法找到元素

[英]Selenium - C# - Webdriver - Unable to find element

Using selenium in C# I am trying to open a browser, navigate to Google and find the text search field. 在C#中使用selen我正在尝试打开浏览器,导航到Google并找到文本搜索字段。

I try the below 我试试下面的

IWebDriver driver = new InternetExplorerDriver(@"C:\");

driver.Navigate().GoToUrl("www.google.com");

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));

IWebElement password = driver.FindElement(By.Id("gbqfq"));

but get the following error - 但得到以下错误 -

Unable to find element with id == gbqfq 无法找到id == gbqfq的元素

This looks like a copy of this question that has already been answered. 这看起来像是已经回答过的这个问题的副本。

I can show you what I've done, which seems to work well for me: 我可以告诉你我做了什么,这似乎对我有用:

public static IWebElement WaitForElementToAppear(IWebDriver driver, int waitTime, By waitingElement)
{
        IWebElement wait = new WebDriverWait(driver, TimeSpan.FromSeconds(waitTime)).Until(ExpectedConditions.ElementExists(waitingElement));
        return wait;
}

This should wait waitTime amount of time until either the element is found or not. 这应该等待waitTime时间,直到找到元素为止。 I've run into a lot of issues with dynamic pages not loading the elements I need right away and the WebDriver trying to find the elements faster than the page can load them, and this is my solution to it. 我遇到了很多问题,动态页面没有立即加载我需要的元素,WebDriver试图找到比页面加载它们更快的元素,这是我的解决方案。 Hope it helps! 希望能帮助到你!

You can try using a spin wait 您可以尝试使用旋转等待

int timeout =0;
while (driver.FindElements(By.id("gbqfq")).Count == 0 && timeout <500){
  Thread.sleep(1);
  timeout++;

 }
 IWebElement password = driver.FindElement(By.Id("gbqfq"));

this should help make sure that the element has actually had time to appear. 这应该有助于确保元素实际上有时间出现。

also note, the "gbqfq" id is kinda a smell. 还要注意,“gbqfq”id有点气味。 I might try something more meaningful to match on than that id. 我可能会尝试一些比id更有意义的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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