如何从网页获取源代码
How do I get source code from a webpage?
我们如何从 php 和/或 javascript 中的网页中获取网页的源代码?
在不使用不必要的框架的 Javascript 中(在示例中 api.codetabs.com 是绕过跨源资源共享的代理):
fetch('https://api.codetabs.com/v1/proxy?quest=google.com').then((response) => response.text()).then((text) => console.log(text));
感谢:
- @PLB
- @Shadow向导
- 获取 iframe 的源代码
- http://www.frihost.com/forums/vt-32602.html
- @Matt考夫林。
首先,您必须知道,您将永远无法在javascript中获取与页面不在同一域中的页面的源代码。(见 http://en.wikipedia.org/wiki/Same_origin_policy)。
在PHP中,这是你这样做的:
file_get_contents($theUrl);
在javascript中,有三种方法:
首先,通过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);
其次,通过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);
第三,通过jQuery: http://jsfiddle.net/edggD/2/
$.get('../edggD',function(data)//Remember, same domain
{
alert(data);
});
按照Google关于fetch()的指南并使用D.Snap答案,你会得到这样的东西:
fetch('https://api.codetabs.com/v1/proxy?quest=URL_you_want_to_fetch')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.text().then(function(data) {
// data contains all the plain html of the url you previously set,
// you can use it as you want, it is typeof string
console.log(data)
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
这样,您使用的是 CORS 代理,在本例中它是 Codetabs CORS 代理。
CORS 代理允许您获取不在同一域中的资源,从而避免同源策略阻止您的请求。您可以查看其他 CORS 代理:
https://nordicapis.com/10-free-to-use-cors-proxies/
使用 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);
});
如果您只想访问源代码,则上述代码中的数据参数包含原始 HTML 源代码。
相关文章:
- 活动选项卡's源代码-获取变量s值
- 如何从函数名称中获取JavaScript的源代码
- 获取函数原型的源代码
- 获取外部javascript的完整源代码
- 如何使用javascript获取页面源代码
- 让浏览器获取源代码并重新编译脚本以进行实时编辑
- Selenium Java-通过JavascriptExecutor获取页面源代码
- 使用jquery获取其他域名网站的源代码
- 使用美丽汤获取“视图元素”代码,而不是“查看源代码”代码
- 如何从 URL HTML 源代码中获取特定信息
- 如何在不获取整个源代码的情况下解析 HTML 源代码
- 加载页面以获取cookie并同时读取源代码
- 获取外部页面的源代码**使用本机JS**
- 在 Python 中使用请求获取页面但不使用源代码,为什么?如何获取源代码
- 如何从网页获取源代码
- 当我使用 JSON 获取源代码时,jquery 自动完成损坏
- 使用 curl 执行 JavaScript 后获取源代码
- 打开一个新的谷歌浏览器标签并获取源代码
- 从JavaScript创建的HTML中获取源代码
- 使用chrome扩展进行查询并获取源代码