2012-05-22 47 views
2

我使用Selenium webdriver进行UI自动化目的。以下是我的示例代码使用硒webdriver获取DOCTYPE C#

IWebDriver driver = new OpenQA.Selenium.IE.InternetExplorerDriver(); 
    string url ="http://stackoverflow.com"; 
    driver.Navigate().GoToUrl(url); 
    string pagesource = driver.PageSource; 

Pageource变量没有doctype。我需要知道W3C validation的DOCTYPE。有什么办法通过硒获取html源码的DOCTYPE?

This thread显示没有办法通过selenium获取HTML源的Doctype,而是可以从.net执行HTTP请求并获取DOCTYPE。我不想为获取DOCTYPE执行单独的HTTP请求。

回答

4

使用FirefoxDriver代替InternetExplorerDriver会为您提供DOCTYPE。不幸的是,这并不能解决你的问题 - 你使用driver获得的源代码。页面源已经被浏览器预处理,所以试图验证代码不会给出可靠的结果。

不幸的是,没有简单的解决方案。

如果您的页面没有密码保护,您可以使用“通过uri验证”方法。

否则您需要获取页面源代码。我知道这样做的两种方式(我在我的项目中都实现了这两种方式)。一个是使用代理。如果您使用的是C#,请查看FiddlerCore。其他的方法是使用JavaScript和XMLHttpRequest进行另一个请求。你可以find example here(搜索XMLHttpRequest的页面)。

1

对于W3C验证基本上我们有3个问题,如果我们通过硒webdriver自动化。

  1. 由于driver.Pagesource不可靠,请获取适当的页面源代码。
  2. 获取HTML源文件的类型。
  3. 处理通过ajax调用呈现的控件。由于我们无法访问页面源代码中的这些控件,因此我们如何获得页面的确切“生成源代码”?

以上所有的东西都可以通过selenium web驱动执行javascript来完成。

在一个名为'htmlsource.txt'的文本文件中存储以下代码片段。


function outerHTML(node){ 
    // if IE, Chrome take the internal method otherwise build one as lower versions of firefox 
     //does not support element.outerHTML property 
    return node.outerHTML || (
     function(n){ 
      var div = document.createElement('div'), h; 
      div.appendChild(n.cloneNode(true)); 
      h = div.innerHTML; 
      div = null; 
      return h; 
     })(node); 
    } 


var outerhtml = outerHTML(document.getElementsByTagName('html')[0]); 
var node = document.doctype; 
var doctypestring=""; 
if(node) 
{ 
    // IE8 and below does not have document.doctype and you will get null if you access it. 

doctypestring = "<!DOCTYPE " 
     + node.name 
     + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') 
     + (!node.publicId && node.systemId ? ' SYSTEM' : '') 
     + (node.systemId ? ' "' + node.systemId + '"' : '') 
     + '>'; 
     } 
     else 

     { 

      // for IE8 and below you can access doctype like this 

     doctypestring = document.all[0].text; 
     } 
return doctypestring +outerhtml ; 

而且现在的C#代码来访问完整的AJAX渲染HTML源代码与文档类型


IJavaScriptExecutor js = (IJavaScriptExecutor)driver; 
      string jsToexecute =File.ReadAlltext("htmlsource.txt"); 
      string completeHTMLGeneratedSourceWithDoctype = (string)js.ExecuteScript(jsToexecute); 
+0

你仍然面临着同样的问题 - 获得HTML代码来自DOM,由浏览器预处理,因此不可靠。 – JacekM

+0

但是对于通过Ajax呈现的控件,是否有任何方法可以进行W3C验证? FiddlerCore将无法提供帮助,因为控件呈现为数据,并且JavaScript会将所有数据转换为HTML控件。 – Sathish