如何将整个文档的HTML作为字符串获取?

326

有没有一种方法在JS中获取整个HTML作为字符串,包括html标签内的内容?

document.documentElement.??

28
唯一正确的答案:https://dev59.com/3nRA5IYBdhLWcg3wzhXZ(**停止给inner/outerHTML答案点赞,它们不提供整个源代码!**) - John
5
document.body.parentElement.innerHTML 翻译为:文档.正文.父元素.内部HTML。 - Radvylf Programs
@John 他们没有提供什么? - B''H Bi'ezras -- Boruch Hashem
@bluejayke doctype和<html>标签本身不包含在innerHTML中,而且doctype在outerHTML中也不存在。请参考paulo62的答案;它给出了两者的输出。 - Pixelated Fish
2
Op 没有要求整个源代码,请冷静一点 John。 - Seth Jeffery
5
不要赞同John加粗的评论!他链接的答案将 && 替换为 &amp;&amp; ,这会破坏所有内联 <script> 标签!你应该使用 document.documentElement.outerHTML ,但请注意它不会获取 <!DOCTYPE html>,所以你需要自己添加。 - joe
17个回答

1
这将起作用,如果您想获取DOCTYPE之外的所有内容:
document.getElementsByTagName('html')[0].outerHTML;

如果您想要doctype,可以使用以下代码:
new XMLSerializer().serializeToString(document.doctype) + document.getElementsByTagName('html')[0].outerHTML;

1
我正在使用outerHTML来处理元素(主要是<html>容器),并且使用XMLSerializer来处理其他任何内容,包括<!DOCTYPE>、位于<html>容器外的随机注释,或者其他可能存在的内容。似乎在<html>元素外部不保留空格,所以我默认使用sep="\n"添加换行符。

function get_document_html(sep="\n") {
    let html = "";
    let xml = new XMLSerializer();
    for (let n of document.childNodes) {
        if (n.nodeType == Node.ELEMENT_NODE)
            html += n.outerHTML + sep;
        else
            html += xml.serializeToString(n) + sep;
    }
    return html;
}

console.log(get_document_html().slice(0, 200));


1
使用querySelector

const html = document.querySelector("html").outerHTML;
console.log(html)


0

我只需要doctype html,就可以在IE11、Edge和Chrome中正常工作。我使用了下面的代码,它运行良好。

function downloadPage(element, event) {
    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
        document.execCommand('SaveAs', '1', 'page.html');
        event.preventDefault();
    } else {
        if(isChrome) {
            element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML));
        }
        element.setAttribute('download', 'page.html');
    }
}

在你的锚点标签中使用类似这样的方式。

<a href="#" onclick="downloadPage(this,event);" download>Download entire page.</a>

例子

    function downloadPage(element, event) {
     var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    
     if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
      document.execCommand('SaveAs', '1', 'page.html');
      event.preventDefault();
     } else {
      if(isChrome) {
                element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML));
      }
      element.setAttribute('download', 'page.html');
     }
    }
I just need doctype html and should work fine in IE11, Edge and Chrome. 

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<p>
<a href="#" onclick="downloadPage(this,event);"  download><h2>Download entire page.</h2></a></p>

<p>Some image here</p>

<p><img src="https://placeimg.com/250/150/animals"/></p>


-1

那个问题应该被关闭,因为它几乎是这个更早的问题的重复。无论如何,有趣的部分是你需要使用.outerHTML并获取document.doctype,最完整的答案是Paolo's - Dan Dascalescu

-3

你需要遍历文档的childNodes并获取outerHTML内容。

在VBA中,它看起来像这样:

For Each e In document.ChildNodes
    Put ff, , e.outerHTML & vbCrLf
Next e

使用此方法,可以获取网页中的所有元素,包括存在的<!DOCTYPE>节点。


-10

正确的方式实际上是:

webBrowser1.DocumentText


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接