Programing

전체 문서 HTML을 문자열로 얻는 방법?

lottogame 2020. 5. 6. 20:50
반응형

전체 문서 HTML을 문자열로 얻는 방법?


JS에서 html 태그 내의 전체 HTML을 문자열 로 가져 오는 방법이 있습니까?

document.documentElement.??

MS는 얼마 전에 outerHTMLand innerHTML속성을 추가했습니다 .

에 따르면 MDN , outerHTML파이어 폭스 (11), 크롬 0.2, 인터넷 익스플로러 4.0, 오페라 7, 사파리 1.3, 안드로이드, 파이어 폭스 모바일 (11), IE 모바일, 오페라 모바일, 사파리 모바일에서 지원됩니다. outerHTMLDOM 구문 분석 및 직렬화 사양입니다.

적합한 기능에 대한 브라우저 호환성에 대해서는 quirksmode참조하십시오 . 모든 지원 innerHTML.

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

넌 할 수있어

new XMLSerializer().serializeToString(document)

IE 9보다 새로운 브라우저에서

참조 https://caniuse.com/#feat=xml-serializer를


나는 document.documentElement.outerHTML당신을 위해 그것을 반환해야 한다고 생각 합니다.

에 따르면 MDN , outerHTML파이어 폭스 (11), 크롬 0.2, 인터넷 익스플로러 4.0, 오페라 7, 사파리 1.3, 안드로이드, 파이어 폭스 모바일 (11), IE 모바일, 오페라 모바일, 사파리 모바일에서 지원됩니다. outerHTMLDOM 구문 분석 및 직렬화 사양입니다.

outerHTML속성 의 MSDN 페이지 는 IE 5 이상에서 지원된다고 설명합니다. Colin의 답변은 W3C quirksmode 페이지로 연결되며, 브라우저 간 호환성을 비교할 수 있습니다 (다른 DOM 기능도 해당).


나는 반환 된 것을보기 위해 다양한 답변을 시도했습니다. 최신 버전의 Chrome을 사용하고 있습니다.

제안이 document.documentElement.innerHTML;돌아 왔습니다<head> ... </body>

개비의 제안 document.getElementsByTagName('html')[0].innerHTML;은 똑 같았다.

제안은 document.documentElement.outerHTML;반환 <html><head> ... </body></html>'DOCTYPE'에서 떨어져 모든이다.

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

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

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


당신은 또한 할 수 있습니다 :

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

Doctype 또는 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에서 작동 할 수 있습니다. (매우 doctype-defs 인 소스 텍스트의 아주 처음부터 VERY FIRST 300자를 표시합니다.)

그러나 FF의 일반 "다른 이름으로 저장"대화 상자는 페이지의 현재 상태를 저장하지 않고 원래로드 된 X / h / tml-source-text를 저장할 수는 없습니다. (일부 임시 파일로 ss를 POST하고 파일로 리디렉션하면 이전에 변경 / 편집 한 내용으로 저장 가능한 소스 텍스트를 제공 할 수 있습니다.)

Although FF surprises by good recovery on "back" and a NICE inclusion of states/values on "Save (as) ..." for input-like FIELDS, textarea etc. , not on elements in contenteditable/ designMode...

If NOT a xhtml- resp. xml-file (mime-type, NOT just filename-extension!), one may use document.open/write/close to SET the the appr. content to the source-layer, that will be saved on user's save-dialog from the File/Save menue of FF. see: http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite resp.

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

Neutral to questions of X(ht)ML, try a "view-source:http://..." as the value of the src-attrib of an (script-made!?) iframe, - to access an iframes-document in FF:

<iframe-elementnode>.contentDocument, see google "mdn contentDocument" for appr. members, like 'textContent' for instance. 'Got that years ago and no like to crawl for it. If still of urgent need, mention this, that I got to dive in ...


document.documentElement.innerHTML

I always use

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

Probably not the right way but I can understand it when I see it.


Use document.documentElement.

Same Question answered here: https://stackoverflow.com/a/7289396/2164160


To also get things outside the <html>...</html>, most importantly the <!DOCTYPE ...> declaration, you could walk through document.childNodes, turning each into a string:

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

I published this code as document-outerhtml on npm.


edit Note the code above depends on a function doctypeToString; its implementation could be as follows (code below is published on npm as doctype-to-string):

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
}


I just need doctype html and should work fine in IE11, Edge and Chrome. I used below code it works fine.

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

and in your anchor tag use like this.

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

Example

    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>


You have to iterate through the document childNodes and getting the outerHTML content.

in VBA it looks like this

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

using this, allows you to get all elements of the web page including < !DOCTYPE > node if it exists


The correct way is actually:

webBrowser1.DocumentText

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

반응형