顯示具有 javascript 標籤的文章。 顯示所有文章
顯示具有 javascript 標籤的文章。 顯示所有文章

2013年12月26日 星期四

使用JavaScript抓取動態生成的網頁

想要得到html檔案的原始碼,最直觀的做法就使用: 

document.getElementsByTagName('html')[0].innerHTML
 
 
document.documentElement.innerHTML 
 
 
document.documentElement.outerHTML

但是這樣無法得到第三方JavaScript所生成的html content

於是可以使用以下函式:
 
  function DOMtoString(document_root) {
    var html = '',
    node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                html += node.outerHTML;
                break;
            case Node.TEXT_NODE:
                html += node.nodeValue;
                break;
            case Node.CDATA_SECTION_NODE:
                html += '<![CDATA[' + node.nodeValue + ']]>';
                break;
            case Node.COMMENT_NODE:
                html += '<!--' + node.nodeValue + '-->';
                break;
            case Node.DOCUMENT_TYPE_NODE:
                // (X)HTML documents are identified by public identifiers
                html += "<!DOCTYPE " + node.name
                    + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
                    + (!node.publicId && node.systemId ? ' SYSTEM' : '') 
                    + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
                break;
        }
        node = node.nextSibling;
    }
    return html;
}

參數document_root,表示使用上述方法所獲取的html content。
 
顧名思義,此函式將會回傳包括JavaScript動態生成的html content

2013年8月21日 星期三

JavaScript的URL編碼

要用GET傳值到下一個頁面常會用:
xxx.html?abc=abc

如果現在是要傳中文:
xxx.html?abc=中文
會顯示UTF-8編碼格式
xxx.html?abc=%E4%B8%AD%E6%96%87

如果想用abc這個參數的值
就可以使用JS內建的 decodeURI() decodeURIComponent() 進行解碼

其他參考資料:
 http://blog.longwin.com.tw/2010/01/javascript-encodeuri-component-utf-8-2010/