[英]Why am I not getting back any images here?
$url = 'http://www.w3schools.com/js/js_loop_for.asp';
$html = @file_get_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$xml = @simplexml_import_dom($doc);
$images = $xml->xpath('//img');
var_dump($images);
die();
輸出是:
array(0) { }
但是,在頁面源代碼中我看到了:
<img border="0" width="336" height="69" src="/images/w3schoolslogo.gif" alt="W3Schools.com" style="margin-top:5px;" />
編輯:看來$html
的內容停在此頁面的<body>
標簽上。 知道為什么嗎?
看來$ html的內容停在此頁面的標簽上。 知道為什么嗎?
是的,您必須為此頁面提供有效的用戶代理。
$url = 'http://www.w3schools.com/js/js_loop_for.asp';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_exec($ch);
將所有內容輸出到結尾</html>
包括你要求的<img border="0" width="336" height="69" src="/images/w3schoolslogo.gif" alt="W3Schools.com" style="margin-top:5px;" />
<img border="0" width="336" height="69" src="/images/w3schoolslogo.gif" alt="W3Schools.com" style="margin-top:5px;" />
當沒有用戶代理的簡單wget或curl僅返回<body>
標記時。
$url = 'http://www.w3schools.com/js/js_loop_for.asp';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec($ch);
$doc = new DOMDocument();
$doc->loadHTML($html);
$xml = simplexml_import_dom($doc);
$images = $xml->xpath('//img');
var_dump($images);
die();
編輯: 我的第一篇文章說xpath還有一個問題......我只是沒有做盡職調查,上面的更新代碼效果很好。 我忘了強制curl輸出到字符串而不是打印到屏幕(默認情況下)。
為什么要將simplexml加入混合? 您已經將w3fools中的HTML加載到DOM類中,該類已經有一個非常好的XPath查詢引擎。
[...snip...]
$doc->loadHTML($html);
$xpath = new DOMXPath($doc)
$images = $xpath->xpath('//img');
[...snip...]
IMG標記由javascript生成。 如果您通過wget下載了此頁面,您會發現HTML中沒有IMG標記。
我相信這是因為用戶代理字符串。 如果我提供“Mozilla / 5.0(X11; Linux i686 on x86_64; rv:2.0)Gecko / 20100101 Firefox / 4.0”作為用戶代理ID,我會得到整個頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.