如何从网页获取源代码?

6

如何在php和/或javascript中从网页获取网页的源代码?


你是在说网页的HTML吗? - Farhan Ahmad
2
file_get_contents($file_or_url); - Leri
1
如果来源域与您的不同,则由于同源策略,您必须使用服务器端语言。否则(相同的域),您可以使用AJAX。 - Shadow The Spring Wizard
谢谢,我能用JS做同样的事情吗? - user1365010
@user1365010 我不熟悉JavaScript,但如果可能的话,我不会在客户端执行此操作。 - Leri
4个回答

10

在不使用不必要的框架的情况下使用Javascript(在示例中,api.codetabs.com是一个代理服务器,用于绕过跨源资源共享):

fetch('https://api.codetabs.com/v1/proxy?quest=google.com').then((response) => response.text()).then((text) => console.log(text));

不是对问题的回答。问题是如何获取“当前”页面的代码,而不是如何查询页面加载的文件的新版本。服务器文件可能会发生变化,甚至可以动态生成。 - undefined

2

感谢:

首先,您必须知道,如果一个页面不在与您的页面相同的域中,您将永远无法在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);
});

忘记XHR中的同源策略吧! ;) - RixTheTyrunt
这并不是问题的答案。问题是如何获取当前页面的代码,而不是如何查询页面加载自的文件的新版本。服务器文件可能会发生变化,甚至是动态生成的。 - undefined

1

使用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源代码。


不是对问题的回答。问题是如何获取当前页面的代码,而不是如何查询页面加载的文件的新版本。服务器文件可能会发生变化,甚至可以动态生成。 - undefined

1

按照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 Proxy

CORS代理允许您获取不在同一域中的资源,从而避免了同源策略阻止您的请求。您可以查看其他CORS代理:

https://nordicapis.com/10-free-to-use-cors-proxies/


不是问题的答案。问题是如何获取当前页面的代码,而不是如何查询页面加载的文件的新版本。服务器文件可以更改甚至可以动态生成。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接