Webdriver没有通过id或类NoSuchElementException找到任何元素

时间:2016-10-12 20:33:35

标签: c# internet-explorer selenium xpath selenium-webdriver

我正试图从公共网站的div中获取数据。 Selenium WebDriver似乎没有找到任何元素。我尝试使用XPath找到具有id和class的元素,但仍然没有找到任何内容。 我在查看PageSource时可以看到html页面代码,这确认了驱动程序的工作原理。我在这做错了什么? Selenium V2.53.1 // IEDriverServer Win32 v2.53.1

我的代码:

    IWebDriver driver = new InternetExplorerDriver("C:\\Program Files\\SeleniumWebPagetester");
    driver.Navigate().GoToUrl("D:\\test.html");
    await Task.Delay(30000);
    var src = driver.PageSource; //shows the html page -> works
    var ds = driver.FindElement(By.XPath("//html//body")); //NoSuchElementException
    var test = driver.FindElement(By.Id("aspnetForm")); //An unhandled exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll
    var testy = driver.FindElement(By.Id("aspnetForm"), 30); //'OpenQA.Selenium.NoSuchElementException'
    var tst = driver.FindElement(By.XPath("//*[@id=\"lx-home\"]"), 30); //'OpenQA.Selenium.NoSuchElementException'
    driver.Quit();

简单的HTML页面:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
    </head>
    <body>
        <form action="#" id="aspnetForm" onsubmit="return false;">
         <section id="lx-home" style="margin-bottom:50px;">
          <div class="bigbanner">
            <div class="splash mc">
              <div class="bighead crb">LEAD DELIVERY MADE EASY</div>
            </div>
          </div>
         </section>
        </form>
    </body>
</html>

旁注,我的XPath与HtmlWeb完美配合:

    string Url = "D:\\test.html";
    HtmlWeb web = new HtmlWeb();
    HtmlDocument doc = web.Load(Url);
    var element = doc.DocumentNode.SelectNodes("//*[@id=\"lx-home\"]"); //WORKS

1 个答案:

答案 0 :(得分:2)

IE似乎以不同的方式解析本地文件,因此您无法访问DOM。您可以选择以下选项:

  1. 使用Chrome代替IE
  2. 继续使用IE,将文件移至C:\inetpub\wwwroot,然后将代码更改为打开URL而不是localfile:driver.Navigate().GoToUrl("http://localhost/test.html");
相关问题