my crawler isn't working. I want it to output
<div class="content">
But when i run it i get this output:
Array ( )
This is my code:
<?php
$dom = new DOMDocument;
@$dom->loadHTML('https://www.google.com/');
$xp = new DOMXPath($dom);
$links = $xp->query('//div[contains(@class,"content")]');
$result = array();
foreach ($links as $link) {
$result[] = array($link->getAttribute("innerHTML"), $link->nodeValue);
}
print_r($result);
?>
DOMDocument::loadHTML()
parses the HTML from the string that you pass it, see the docs . In your case the string is https://www.google.com/
which is obviously not valid HTML.
You could use cURL to retrieve the actual HTML from the page. I made a few quick tests and seems that Google's response varies with the user agent, so you could use a real one, eg
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36');
$html = trim(curl_exec($ch));
curl_close($ch);
$dom = new DOMDocument;
@$dom->loadHTML($html);
// rest of the code
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.