Html 使用 DOMdocument 解析和抓取 URL

Html parsing and grabbing URL's by using DOMdocument

试图抓住 URLs。但是我的 foreach 循环只是 returns 来自前两个 <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循环错了吗?或者是网站有一些 obsticle 是 停止刮擦?谢谢你帮我。

您可以使用 simple_html_dom 获得想要的结果。我使用这个库是因为它支持 css 选择器。试试下面的脚本。

<?php
include("simple_html_dom.php");

$weblink = "http://www.sumitomo-rd-mansion.jp/kansai/";
function fetch_sumitomo_links($weblink)
{
    $htmldoc   = file_get_html($weblink);
    foreach ($htmldoc->find(".name a") as $a) {
        $links[]          = $a->href . '<br>';
    }
    return $links;
}
$items = fetch_sumitomo_links($weblink);
foreach($items as $itemlinks){
    echo $itemlinks;
}
?>

我知道已经有一个公认的答案,但我不建议使用这个 "simple_html_dom" 库,它已有 10 多年的历史并且很长一段时间都没有开发。我建议您坚持使用 DomDocument,并且可以使用 XPath 查询来避免您执行的所有循环:

<?php
$xpath = new \DOMXPath($parser);
$nodes = $xpath->query("//div[@id='areaWrap']//div[contains(@class, 'areaBox')]//a[1]");
foreach ($nodes as $node) {
    $links[] = $node->getAttribute("href");
}

您在使用此页面时遇到的问题是 HTML 中的数据无效。如果你去掉 libxml_use_internal_errors(true); 你会看到与无效字符相关的警告。在您的 getSiteContent 函数中,您可以在将文本加载到 DomDocument 之前转换文本:

$html = mb_convert_encoding($html, "SJIS", "UTF-8");

这给出了预期的输出:

array(7) {
  [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"
  [2]=>
  string(60) "http://www.sumitomo-rd-mansion.jp/kansai/kyobashi/index.html"
  [3]=>
  string(59) "http://www.sumitomo-rd-mansion.jp/kansai/tsurumi/index.html"
  [4]=>
  string(62) "http://www.sumitomo-rd-mansion.jp/kansai/kitatanabe/index.html"
  [5]=>
  string(47) "http://sumai.tokyu-land.co.jp/branz/umedanorth/"
  [6]=>
  string(63) "http://www.sumitomo-rd-mansion.jp/kansai/momoyamadai/index.html"
}