对于 W3C 验证,如果我们通过 selenium webdriver 进行自动化,基本上我们会遇到 3 个问题。
- 由于 driver.Pagesource 不可靠,因此获取正确的页面源。
- 获取 HTML 源的 doctype。
- 处理通过 ajax 调用呈现的控件。由于我们无法在页面源中访问这些控件,我们如何获得页面的确切“生成源”?
上述所有事情都可以通过 selenium web driver 执行 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 ;
现在使用 doctype 访问完整的 AJAX 呈现的 HTML 源的 C# 代码
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string jsToexecute =File.ReadAlltext("htmlsource.txt");
string completeHTMLGeneratedSourceWithDoctype = (string)js.ExecuteScript(jsToexecute);