试图抓取 URL。但我的foreach循环只返回前两个<div>元素的 URL。它不会更进一步。
功能:
function getSiteContent($url)
{
$html = cache()->rememberForever($url, function () use ($url) {
return file_get_contents($url);
});
$parser = new \DOMDocument();
$parser->loadHTML($html);
return $parser;
}
代码:
libxml_use_internal_errors(true);
$url = 'http://www.sumitomo-rd-mansion.jp/kansai/';
$parser = getSiteContent($url);
$allDivs = $parser->getElementsByTagName('div');
foreach ($allDivs as $div) {
if ($div->getAttribute('id') == 'areaWrap') {
$innerDivs = $div->getElementsByTagName('div');
foreach ($innerDivs as $innerDiv) {
if ($innerDiv->getAttribute('class') == 'areaBox clearfix') {
$links = $innerDiv->getElementsByTagName('a');
if ($links->length > 0) {
$a = $links->item(0);
$linkRef = $a->getAttribute('href');
$link [] = $linkRef;
}
}
}
}
}
var_dump($link);
结果:
array(2) {
[0]=>
string(65) "http://www.sumitomo-rd-mansion.jp/kansai/higashi_umeda/index.html"
[1]=>
string(60) "http://www.sumitomo-rd-mansion.jp/kansai/osaka745/index.html"
}
有了这段代码,我就得到了第一个和第二个 div areaBox。并停在那里。我的 foreach 循环错了吗?还是网站有一些阻止刮擦的障碍?谢谢你帮助我。