如何获得整个文档HTML的字符串?

问题描述 投票:232回答:15

JS中是否有一种方法可以将html标记内的整个HTML作为字符串获取?

document.documentElement.??
javascript html document tostring
15个回答
314
投票

MS不久前添加了outerHTMLinnerHTML属性。

根据MDN,在Firefox 11,Chrome 0.2,Internet Explorer 4.0,Opera 7,Safari 1.3,Android,Firefox Mobile 11,IE Mobile,Opera Mobile和Safari Mobile中支持outerHTMLouterHTMLDOM Parsing and Serialization规格中。

请参阅quirksmode以了解适合您的浏览器兼容性。全部支持innerHTML

var markup = document.documentElement.innerHTML;
alert(markup);

74
投票

您可以做

new XMLSerializer().serializeToString(document)

在比IE 9更高的浏览器中

请参见https://caniuse.com/#feat=xml-serializer


43
投票

我相信document.documentElement.outerHTML应该为您退还该款项。

根据MDN,在Firefox 11,Chrome 0.2,Internet Explorer 4.0,Opera 7,Safari 1.3,Android,Firefox Mobile 11,IE Mobile,Opera Mobile和Safari Mobile中支持outerHTMLouterHTMLDOM Parsing and Serialization规格中。

outerHTML property上的MSDN页面指出,它在IE 5+中受支持。 Colin的答案链接到W3C quirksmode页面,该页面很好地比较了跨浏览器的兼容性(也适用于其他DOM功能)。


39
投票

我尝试了各种答案以查看返回了什么。我正在使用最新版本的Chrome。

建议outerHTML返回了document.documentElement.innerHTML;

Gaby的建议<head> ... </body>返回了相同的结果。

建议document.getElementsByTagName('html')[0].innerHTML;返回了document.documentElement.outerHTML;除了“ doctype”之外,这是所有内容。

您可以使用<html><head> ... </body></html>检索doctype对象,这将返回一个对象,而不是字符串,因此,如果您需要提取所有文档类型的详细信息作为字符串,直到并包括HTML5,请在此处进行描述:document.doctype;

我只想要HTML5,所以下面的内容足以创建整个文档:

Get DocType of an HTML as string with Javascript


10
投票

您也可以这样做:

alert('<!DOCTYPE HTML>' + '\n' + document.documentElement.outerHTML);

您将不会获得Doctype或html标记,但会获得其他所有内容...


5
投票
document.getElementsByTagName('html')[0].innerHTML

4
投票

仅可能是IE:

document.documentElement.outerHTML

对于FF从1.0开始:

>     webBrowser1.DocumentText

可以在FF中使用。 (从源文本的非常开头开始显示非常300个字符,主要是doctype-defs。)

但是请注意,FF的常规“另存为”对话框可能不会保存页面的当前状态,而不会保存最初加载的X / h / tml-source-text!(将ss张贴到某些临时文件并重定向到该临时文件可能会提供可保存的源文本,其中包含对其进行的更改/编辑。)

尽管FF使“ back”的恢复良好,并且在“ Save(as)...”上包含状态/值的NICE令人惊讶,对于类似输入的FIELDS,textarea等,而不是contenteditable /中的元素/ designMode ...

如果不是xhtml-, xml文件(MIME类型,而不仅仅是文件扩展名!),可以使用document.open/write/close来设置appr。内容保存到源层,这些内容将从FF的“文件/保存”菜单保存在用户的“保存”对话框中。看到://serialize current DOM-Tree incl. changes/edits to ss-variable var ns = new XMLSerializer(); var ss= ns.serializeToString(document); alert(ss.substr(0,300)); 对应

http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite

对于X(ht)ML的问题中性,请尝试使用“ view-source:http:// ...”作为(脚本制作的!?)iframe的src-attrib的值,以访问- FF中的iframes文档:

https://developer.mozilla.org/en-US/docs/Web/API/document.write,请参阅google“ mdn contentDocument” for appr。成员,例如'textContent'。``那是几年前的事,并且不喜欢它爬行。如果仍然有紧急需要,请提一下,我要潜入...


2
投票
<iframe-elementnode>.contentDocument

1
投票

使用document.documentElement.innerHTML

相同的问题在这里回答:document.documentElement


1
投票

[也可以使内容超出https://stackoverflow.com/a/7289396/2164160,最重要的是<html>...</html>声明,您可以遍历document.childNodes,将它们转换为字符串:

<!DOCTYPE ...>

我在npm将此代码发布为const html = [...document.childNodes] .map(node => nodeToString(node)) .join('\n') // could use '' instead, but whitespace should not matter. function nodeToString(node) { switch (node.nodeType) { case node.ELEMENT_NODE: return node.outerHTML case node.TEXT_NODE: // Text nodes should probably never be encountered, but handling them anyway. return node.textContent case node.COMMENT_NODE: return `<!--${node.textContent}-->` case node.DOCUMENT_TYPE_NODE: return doctypeToString(node) default: throw new TypeError(`Unexpected node type: ${node.nodeType}`) } }


edit注意,上面的代码取决于功能document-outerhtml;它的实现可以如下(以下代码在npm上以doctypeToString的形式发布):

doctype-to-string


0
投票

我一直使用

function doctypeToString(doctype) {
    if (doctype === null) {
        return ''
    }
    // Checking with instanceof DocumentType might be neater, but how to get a
    // reference to DocumentType without assuming it to be available globally?
    // To play nice with custom DOM implementations, we resort to duck-typing.
    if (!doctype
        || doctype.nodeType !== doctype.DOCUMENT_TYPE_NODE
        || typeof doctype.name !== 'string'
        || typeof doctype.publicId !== 'string'
        || typeof doctype.systemId !== 'string'
    ) {
        throw new TypeError('Expected a DocumentType')
    }
    const doctypeString = `<!DOCTYPE ${doctype.name}`
        + (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
        + (doctype.systemId
            ? (doctype.publicId ? `` : ` SYSTEM`) + ` "${doctype.systemId}"`
            : ``)
        + `>`
    return doctypeString
}

可能不是正确的方法,但是看到它我就能理解。


0
投票

我只需要doctype html,并且应该可以在IE11,Edge和Chrome中正常工作。我用下面的代码工作正常。

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

并且在您的锚标记中这样使用。

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');
    	}
    }

0
投票

我将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>用于元素(主outerHTML容器),并将<html>用于其他任何内容,包括XMLSerializer<!DOCTYPE>容器外部的随机注释或其他可能存在的内容。似乎在<html>元素外部没有保留空格,因此默认情况下我使用<html>添加换行符。

sep="\n"

-1
投票

您必须遍历文档childNodes并获取externalHTML内容。

在VBA中看起来像这样

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));

使用它,您可以获取网页的所有元素,包括节点(如果存在)


-9
投票

正确的方法实际上是:

webBrowser1.DocumentText

© www.soinside.com 2019 - 2024. All rights reserved.