简体   繁体   中英

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.

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

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. 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. 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. I might try something more meaningful to match on than that id.

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