微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 从其他网站获取HTML内容

我想从另一个网站动态检索html内容,我得到了公司的许可.

请不要指向JSONP,因为我无法编辑站点A,只能编辑站点B.

解决方法:

由于跨域安全问题,您将无法执行此客户端,除非您满足于iframe.

使用PHP,您可以使用几种“抓取”内容方法.您使用的方法取决于您是否需要在请求中使用cookie(即数据是在登录后面).

无论哪种方式,要在客户端启动,您将向您自己的服务器发出标准的AJAX请求:

$.ajax({
  type: "POST",
  url: "localProxy.PHP",
  data: {url: "maybe_send_your_url_here.PHP?product_id=1"}
}).done(function( html ) {
   // do something with your HTML!
});

如果你需要设置cookie(如果远程站点需要登录,你需要他们),你将使用cURL.使用发布数据和接受cookie登录的完整机制有点超出了这个答案的范围,但您的请求看起来像这样:

$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL, 'http://thirdpartydomain.internet/login_url.PHP'); 
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); 
curl_setopt ($ch, CURLOPT_TIMEOUT, 60); 
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.jar'); 
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'email='.$username.'&password='.$password); 
curl_setopt ($ch, CURLOPT_POST, 1); 
$result = curl_exec ($ch); 
curl_close($ch);

此时,您可以检查$result变量并确保登录有效.如果是这样,那么您将使用cURL发出另一个请求以获取页面内容.第二个请求不会包含所有post junk,并且您将使用您尝试获取的URL.你最终会得到一个充满HTML的大字符串.

如果您只需要该页面内容的一部分,可以使用下面的方法将字符串加载到DomDocument中,使用loadHTML方法而不是loadHTMLFile(参见下文)

说到DomDocument,如果你不需要cookie,那么你可以直接使用DomDocument获取页面,跳过cURL:

$doc = new DOMDocument('1.0', 'UTF-8');
// load the string into the DOM (this is your page's HTML), see below for more info
$doc->loadHTMLFile ('http://third_party_url_here.PHP?query=string');

// since we are working with HTML fragments here, remove <!DOCTYPE 
$doc->removeChild($doc->firstChild);            

// remove <html></html> and any junk
$body = $doc->getElementsByTagName('body'); 
$doc->replaceChild($body->item(0), $doc->firstChild);

// Now, you can get any portion of the html (target a div, for example) using familiar DOM methods

// echo the HTML (or desired portion thereof)
die($doc->saveHTML());

文档

> MDN上的HTML iframe – https://developer.mozilla.org/en/HTML/Element/iframe
> jQuery.ajax() – http://api.jquery.com/jQuery.ajax/
> PHP的cURL – http://php.net/manual/en/book.curl.php
> Curl :: set_opt(关于使用cookie的信息) – http://www.php.net/manual/en/function.curl-setopt.php
> PHP的DomDocument – http://php.net/manual/en/class.domdocument.php
> DomDocument :: loadHTMLFile – http://www.php.net/manual/en/domdocument.loadhtmlfile.php
> DomDocument :: loadHTML – http://www.php.net/manual/en/domdocument.loadhtml.php

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐