我想从另一个网站动态获取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 发出另一个请求来抓取页面内容。第二个请求不会包含所有垃圾邮件,您将使用您尝试获取的 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.phpDomDocument::loadHTML
- http://www.php.net/manual/en/domdocument.loadhtml.php
关于javascript - 从另一个站点获取 HTML 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11438864/