首页 > 解决方案 > 使用 if 语句通过 Xpath 获取数据

问题描述

我有三个 URL,这些 URL 包含我想要的数据。但是每个数据中的html标签不同。所以这就是为什么我不能为所有人提供相同的 Xpath。我需要尝试“如果在这个 Xpath 中找不到它,那么试试这个。” 像一种方式。但我对如何做到这一点有点困惑?

例如,这些是链接$linkBox

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

我将一一进入这些链接。而对于第一个。我给 Xpath:

$get = [];
    foreach ($linkBox as $box){
        $content = pageContent($box);
            $Pars = new \DOMXPath($content);
            $Route = $Pars->query("//ul[@id='snav']/li/a");
            foreach ($Route as $Rot){
                $get = $Rot->getAttribute('href');
            }

    }

但是 Xpath 不适合第二个或第三个。因此,如果使用 if 语句,如果它为空,我该如何编写试试这个?像代码?我能做到吗?还是我需要使用其他方式?

第二个 Box 的 Xpath 是:

 $Route = $Pars->query("//nav[@id='siteActionNav']ul/li/a");

第二个 Box 的 Xpath 是:

 $Route = $Pars->query("//ul[@id='subNavi']/li[2]/a");

标签: phpweb-scraping

解决方案


您可以做的是尝试每个 XPath 表达式并查看它是否返回任何元素。

例如,这是一个依次测试每个表达式的函数,DOMNodeList如果找到任何匹配项则返回 a,否则抛出异常......

function findLinks(\DOMXPath $xp) {
    $queries = [
        '//ul[@id="snav"]/li/a', 
        '//nav[@id="siteActionNav"]ul/li/a', 
        '//ul[@id="subNavi"]/li[2]/a'
    ];
    foreach ($queries as $query) {
        $links = $xp->query($query);
        if ($links->length > 0) {
            return $links; // exits the function and returns the list
        }
    }
    throw new \RuntimeException('No links found');
}

然后你可以像这样使用它

foreach ($linkBox as $box){
    $content = pageContent($box);
    try {
        $links = findLinks(new \DOMXPath($content));
        foreach ($links as $link){
            $get[] = $link->getAttribute('href'); // note: changed to a push
        }
    } catch (\Exception $e) {
        echo "Problem with $box: " . $e->getMessage();
    }
}

推荐阅读