programing

전체 문서 HTML을 문자열로 가져오려면 어떻게 해야 합니까?

firstcheck 2022. 10. 18. 21:57
반응형

전체 문서 HTML을 문자열로 가져오려면 어떻게 해야 합니까?

JS에서 HTML 태그 전체를 문자열로 가져올 수 있는 방법이 있습니까?

document.documentElement.??

MS가 추가한 것은outerHTML그리고.innerHTML얼마 전에 부동산에 등록했습니다.

MDN에 따르면outerHTML는 Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile 및 Safari Mobile에서 지원됩니다. outerHTML는 DOM 해석시리얼화 사양에 기재되어 있습니다.

사용자에게 적합한 브라우저 호환성에 대해서는 쿼크스 모드를 참조하십시오.모든 지원innerHTML.

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

할수있습니다

new XMLSerializer().serializeToString(document)

IE 9보다 새로운 브라우저의 경우

https://caniuse.com/ #syslog=xml-syslogizer 를 참조해 주세요.

믿어요document.documentElement.outerHTML돌려드릴 겁니다

MDN에 따르면outerHTML는 Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile 및 Safari Mobile에서 지원됩니다. outerHTML는 DOM 해석시리얼화 사양에 기재되어 있습니다.

속성의 MSDN 페이지에는 IE 5+에서 지원되는 것이 나와 있습니다.Colin의 답변은 W3C Quirksmode 페이지로 링크되어 크로스 브라우저 호환성을 잘 비교할 수 있습니다(기타 DOM 기능에도 해당).

나는 무엇이 돌아오는지 보기 위해 여러 가지 답을 시도했다.저는 최신 버전의 크롬을 사용하고 있습니다.

제안사항document.documentElement.innerHTML;반환했다<head> ... </body>

가비의 제안document.getElementsByTagName('html')[0].innerHTML;같은 것을 반환했습니다.

제안사항document.documentElement.outerHTML;반환했다<html><head> ... </body></html>그것은 '도이프'를 제외한 모든 것이다.

다음을 사용하여 doctpe 개체를 검색할 수 있습니다.document.doctype;문자열이 아닌 개체를 반환하므로 HTML5까지를 포함한 모든 doctype에 대한 세부 정보를 문자열로 추출해야 하는 경우 다음과 같이 설명합니다: Javascript를 사용하여 HTML의 DocType을 문자열로 가져옵니다.

HTML5만 원했기 때문에 문서 전체를 작성하기에 충분했습니다.

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

다음 작업도 가능합니다.

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

Doctpe 또는 html 태그는 얻을 수 없지만, 다른 모든 것은...

document.documentElement.outerHTML

아마도 IE만:

>     webBrowser1.DocumentText

FF가 1.0보다 높은 경우:

//serialize current DOM-Tree incl. changes/edits to ss-variable
var ns = new XMLSerializer();
var ss= ns.serializeToString(document);
alert(ss.substr(0,300));

FF로 사용할 수 있습니다. (원문 텍스트의 맨 앞부분에서 가장 먼저 300자를 표시하며, 대부분 doctype-def를 표시합니다.)

다만, 통상의 「다른 이름으로 보존」대화상자는 페이지의 현재 상태를 보존하지 않는 것이 아니라, 원래 로딩되어 있던 X/h/tml-source-text!!(s의 POST-up을 일부 임시 파일에 송신해, 그 이전에 행해진 변경/수정 가능한 소스 텍스트로 리다이렉트 하는 것에 주의해 주세요).

FF는 "뒤로"의 양호한 복구와 "다른 이름으로 저장"에 상태/값의 NICE를 포함시켜 놀라움을 주지만, 컨텐츠 가능/설계 모드의 요소가 아닌 입력과 같은 필드, 텍스트 영역 등에 대해서는...

xhtml-resp이 아닌 경우.xml-file(fileename-type, filename-filename-close가 아닌 document.open/write/close)을 사용하여 소스 계층으로 콘텐츠를 설정할 수 있습니다.이것은 FF의 파일/저장 메뉴에서 사용자의 저장 대화상자에 저장됩니다.http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite response를 참조하십시오.

https://developer.mozilla.org/en-US/docs/Web/API/document.write

X(ht)ML 질문에 대해 중립적으로 (스크립트 작성!?)의 src-attribute 값으로 "view-source:http://..."를 사용해 보십시오.) iframe, - FF의 iframe 문서에 액세스하려면:

<iframe-elementnode>.contentDocumenttextContent와 같은 어플리케이션 구성원에 대한 구글 "mdn contentDocument"를 참조하십시오.'그건 몇 년 전에 생겼는데, 기어다니고 싶지 않아.'그래도 긴급한 일이 있다면, 이걸 언급해 주세요. 제가 뛰어들어야 하는...

document.documentElement.innerHTML

외부로 물건을 가져가기 위해서도<html>...</html>, 가장 중요한 것은<!DOCTYPE ...>declaration을 사용하면 document.childNodes를 통해 각 항목을 문자열로 변환할 수 있습니다.

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}`)
    }
}

저는 이 코드를 document-outerhtml로 npm에 공개했습니다.


편집: 위의 코드는 기능에 따라 다릅니다.doctypeToString; 구현은 다음과 같습니다(아래 코드는 doctpe-to-string으로 npm에 게시됩니다).

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
}

나는 항상 사용한다

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

아마 올바른 방법은 아닐 테지만 보면 알 수 있어요.

사용하고 있다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));

사용하다document.documentElement.

같은 질문에 대한 답변은 다음과 같습니다.https://stackoverflow.com/a/7289396/2164160

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>

DOSCTYPE 외부에서 모든 것을 얻으려면 이 방법이 효과적입니다.

document.getElementsByTagName('html')[0].outerHTML;

또는 다음을 수행할 수 있습니다.

new XMLSerializer().serializeToString(document.doctype) + document.getElementsByTagName('html')[0].outerHTML;

문서 childNodes를 반복하여 외부 노드를 가져와야 합니다.HTML 콘텐츠

VBA에서는 다음과 같습니다.

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

이를 사용하여 웹 페이지의 모든 요소를 가져올 수 있습니다(존재하는 경우).

올바른 방법은 다음과 같습니다.

webBrowser1 。문서본문

언급URL : https://stackoverflow.com/questions/817218/how-to-get-the-entire-document-html-as-a-string

반응형