除非我使用断点,否则我的 selenium 代码中会出现 NoSuchElementException

I get a NoSuchElementException in my selenium code unless I use a breakpoint

我在使用 Selenium 代码时遇到问题,当我 运行 带有断点的代码时它运行良好,没有断点我得到一个异常...

这是代码:

IWebElement myField4 = driver.FindElement(By.Name("login_1method"));
myField4.Click();

IWebElement myField5 = driver.FindElement(By.CssSelector("body > div.content-wrapper.landing-page > div:nth-child(2) > div:nth-child(1) > article > section > ul > li:nth-child(1) > a"));
myField5.Click();

代码在没有断点的 myfield5 处给出了错误,但如果它在第一行的断点处暂停,则可以正常工作。

错误

NoSuchElementException was unhandled

WebDriver 运行 很快。您可以使用显式等待 expected conditions 来允许 WebElement 加载

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("body > div.content-wrapper.landing-page > div:nth-child(2) > div:nth-child(1) > article > section > ul > li:nth-child(1) > a"))).Click();

wait.Until returns 您正在等待的元素,因此您可以使用它来发送点击。