对于W3C验证基本上我们有3个问题,如果我们通过硒webdriver自动化。
- 由于driver.Pagesource不可靠,请获取适当的页面源代码。
- 获取HTML源文件的类型。
- 处理通过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);
你仍然面临着同样的问题 - 获得HTML代码来自DOM,由浏览器预处理,因此不可靠。 – JacekM
但是对于通过Ajax呈现的控件,是否有任何方法可以进行W3C验证? FiddlerCore将无法提供帮助,因为控件呈现为数据,并且JavaScript会将所有数据转换为HTML控件。 – Sathish