1

试图抓取 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 循环错了吗?还是网站有一些阻止刮擦的障碍?谢谢你帮助我。

4

2 回答 2

1

您可以使用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;
}
?>
于 2018-10-23T06:41:06.210 回答
1

我知道已经有一个公认的答案,但我不建议使用这个“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"
}
于 2018-10-31T03:23:25.787 回答