OpenQA.Selenium.NoSuchElementException:使用Selenium和C#在页面上定位元素时,无法找到元素错误

问题描述 投票:1回答:1

我正在尝试在页面睡觉中抓取文本edited out the site

它具有css选择器:

#autocplt_wrap > ul:nth-child(1) > li:nth-child(1) > span:nth-child(1) > a:nth-child(1)

和x-Path:

/html/body/div[2]/div[1]/div[3]/div[2]/div[1]/div/div[1]/div[2]/div/div/ul[1]/li/span/a[1]

我的代码是:

IWebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
//load webdriver
driver.Manage();
driver.Navigate().GoToUrl("https://dict.naver.com/linedict/zhendict/#/cnen/home");
driver.FindElement(By.ClassName("ac_input")).SendKeys("睡觉" + Keys.Enter);
driver.FindElement(By.CssSelector("#autocplt_wrap > ul:nth-child(1) > li:nth-child(1) > span:nth-child(1) > a:nth-child(1)"));

无论我尝试什么,我总是会收到错误:

Unhandled exception. OpenQA.Selenium.NoSuchElementException: Unable to locate element: #autocplt_wrap > ul:nth-child(1) > 
li:nth-child(1) > span:nth-child(1) > a:nth-child(1)
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.By.<>c__DisplayClass29_0.<CssSelector>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
c# selenium xpath css-selectors webdriverwait
1个回答
1
投票

所需元素是动态元素,因此要提取文本睡觉,您必须为所需ElementIsVisible()引入WebDriverWait,并且可以使用以下任何一个Locator Strategies

  • CssSelector

    Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("a.srchword[data-entryid]"))).GetAttribute("innerHTML"));
    
  • XPath

    Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[@class='srchword' and @data-entryid]"))).GetAttribute("innerHTML"));
    

DotNetSeleniumExtras.WaitHelpers一起使用nuget

  • CssSelector

    Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("a.srchword[data-entryid]"))).GetAttribute("innerHTML"));
    
  • XPath

    Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//a[@class='srchword' and @data-entryid]"))).GetAttribute("innerHTML"));
    

您可以在WebDriverWait is not waiting for the element I specify中找到相关的讨论


参考

您可以在NoSuchElementException中找到一些相关的讨论:

© www.soinside.com 2019 - 2024. All rights reserved.