W3C 検証では、基本的に、Selenium webdriver を介して自動化すると、3 つの問題があります。
- driver.Pagesource は信頼できないため、適切なページ ソースを取得しています。
- HTML ソースの doctype を取得しています。
- 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 ;
そして、doctype を使用して AJAX でレンダリングされた完全な HTML ソースにアクセスするための C# コード
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string jsToexecute =File.ReadAlltext("htmlsource.txt");
string completeHTMLGeneratedSourceWithDoctype = (string)js.ExecuteScript(jsToexecute);