javascript 如何从网页中获取源代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10932226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get source code from a webpage?
提问by user1365010
How can we get the source code of a webpage from a webpage in php and/or javascript?
我们如何从 php 和/或 javascript 中的网页获取网页的源代码?
回答by Mageek
Thanks to:
谢谢:
- @PLB
- @Shadow Wizard
- Getting the source code of an iframe
- http://www.frihost.com/forums/vt-32602.html
- @Matt Coughlin.
- @PLB
- @影子向导
- 获取 iframe 的源代码
- http://www.frihost.com/forums/vt-32602.html
- @马特考夫林。
First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).
首先,您必须知道,您将永远无法在 javascript 中获取与您的页面不在同一域中的页面的源代码。(参见http://en.wikipedia.org/wiki/Same_origin_policy)。
In PHP, this is how you do it :
在 PHP 中,您可以这样做:
file_get_contents($theUrl);
In javascript, there is three ways :
在javascript中,有三种方式:
Firstly, by XMLHttpRequest :http://jsfiddle.net/635YY/1/
首先,通过 XMLHttpRequest :http : //jsfiddle.net/635YY/1/
var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);
Secondly, by iFrames :http://jsfiddle.net/XYjuX/1/
其次,通过 iFrames:http : //jsfiddle.net/XYjuX/1/
var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);
Thirdly, by jQuery :http://jsfiddle.net/edggD/2/
第三,通过 jQuery:http : //jsfiddle.net/edggD/2/
$.get('../edggD',function(data)//Remember, same domain
{
alert(data);
});
回答by Matt Coughlin
Ajax example using jQuery:
使用 jQuery 的 Ajax 示例:
// Display the source code of a web page in a pre tag (escaping the HTML).
// Only works if the page is on the same domain.
$.get('page.html', function(data) {
$('pre').text(data);
});
If you just want access to the source code, the data parameter in the above code contains the raw HTML source code.
如果您只想访问源代码,则上述代码中的 data 参数包含原始 HTML 源代码。
回答by D.Snap
In Javascript without using unnecessary frameworks (in the example api.codetabs.com is a proxy to bypass Cross-Origin Resource Sharing):
在 Javascript 中不使用不必要的框架(在示例中 api.codetabs.com 是绕过跨源资源共享的代理):
fetch('https://api.codetabs.com/v1/proxy?quest=google.com').then((response) => response.text()).then((text) => console.log(text));