我想从其他网站动态检索html内容,我得到了公司的许可。
请不要指向JSONP,因为我无法编辑站点A,只能编辑站点B
答案 0 :(得分:6)
由于跨域安全问题,您将无法执行此客户端,除非您对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());
<强>文档强>
iframe
- https://developer.mozilla.org/en/HTML/Element/iframe jQuery.ajax()
- http://api.jquery.com/jQuery.ajax/ cURL
- http://php.net/manual/en/book.curl.php Curl::set_opt
(有关使用Cookie的信息) - http://www.php.net/manual/en/function.curl-setopt.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