【问题标题】:DOMdocument and Xpath array issueDOMdocument 和 Xpath 数组问题
【发布时间】:2019-04-09 10:30:52
【问题描述】:

我在 file_get_contents 和 DOMdocument 以及 Xpath 方面遇到了一些麻烦。

我正在尝试进行一些抓取。 所以我为网站链接做了一个数组。

array(9) {
  [0]=>
  string(34) "https://lions-mansion.jp/MF081014/"
  [1]=>
  string(34) "https://lions-mansion.jp/MF161026/"
  [2]=>
  string(34) "https://lions-mansion.jp/MF171045/"
  [3]=>
  string(34) "https://lions-mansion.jp/MF161016/"
  [4]=>
  string(34) "https://lions-mansion.jp/MF171010/"    
}

尝试使用 foreach 进入这些链接。并尝试抓取链接rel的href!

foreach ($siteUrls as $sites){
        @$html [] = file_get_contents($sites);
}



foreach ($html as $geturl)
{
    $grabber = new \DOMXPath($geturl);
    $mainLink [] = $grabber->query("//link[@rel='canonical']/@href");

}
    var_dump($mainLink);

但最终面临这个错误。

传递给 DOMXPath::__construct() 的参数 1 必须是 DOMDocument,给定字符串

知道如何解决这个问题吗?我怎样才能得到那个link rel url?从头标签

【问题讨论】:

    标签: php laravel xpath domdocument


    【解决方案1】:

    libxml_use_internal_errors:禁用libxml错误并允许用户根据需要获取错误信息http://php.net/manual/en/function.libxml-use-internal-errors.php

    <?php
    
    $siteUrls = [
        "https://lions-mansion.jp/MF081014/",
        "https://lions-mansion.jp/MF161026/",
        "https://lions-mansion.jp/MF171045/",
        "https://lions-mansion.jp/MF161016/",
        "https://lions-mansion.jp/MF161016/"
    ];
    
    foreach ($siteUrls as $sites){
        @$html [] = file_get_contents($sites);
    }
    
    
    libxml_use_internal_errors(true);
    
    foreach ($html as $geturl)
    {
        $dom = new DOMDocument();
        $dom->loadHTML($geturl);
        $grabber = new DOMXPath($dom);
        $names = $grabber->query("//link[@rel='canonical']/@href");
        foreach($names as $contextNode) {
            $mainLink[] = $contextNode->value;
        }
    }
    libxml_clear_errors();
    var_dump($mainLink);
    
    
    array (size=2)
      0 => string 'https://lions-mansion.jp/MF161026/' (length=34)
      1 => string 'https://lions-mansion.jp/MF171045/' (length=34)
    

    【讨论】:

    • 朋友,你也可以检查一下这个问题吗? stackoverflow.com/questions/53166226/…
    • 我正在检查你的新问题。
    • @Snickers 我将在线约 4 小时。我会回答你的新问题。
    • 我希望,你来找出麻烦伙伴 :) 还在等待!
    • @Snickers 从你的新问题中阅读我的 cmets。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2012-09-14
    • 2021-03-09
    • 2016-10-01
    • 1970-01-01
    相关资源
    最近更新 更多