【问题标题】:Append <li> innertext to php url scraper results将 <li> 内文附加到 php url scraper 结果
【发布时间】:2021-01-06 08:30:53
【问题描述】:

我在一页上有一个链接列表:

<li><span><a href="https://site1.com">site1.com</a> : Description 1</span></li>
<li><span><a href="https://site2.com">site2.com</a> : Description 2</span></li>
<li><span><a href="https://site3.com">site3.com</a> : Description 3</span></li>
<li><span><a href="https://site4.com">site4.com</a> : Description 4</span></li>

我正在使用 php 从一个页面获取链接并将它们显示在另一个页面上:

<?php
$urlContent = file_get_contents('https://www.example.com/');

$dom = new DOMDocument();
@$dom->loadHTML($urlContent);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for($i = 0; $i < $hrefs->length; $i++){
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    $url = filter_var($url, FILTER_SANITIZE_URL);
    if(!filter_var($url, FILTER_VALIDATE_URL) === false){
        echo '<a href="'.$url.'">'.$url.'</a><br />';
    }
}
?>

但是,我想弄清楚的是如何在链接旁边包含说明。 这是我的众多尝试之一:

<?php
$urlContent = file_get_contents('https://www.example.com');

$dom = new DOMDocument();
@$dom->loadHTML($urlContent);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a/li");
$li = document.getElementsByTagName("li");

for($i = 0; $i < $hrefs->length; $i++){
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    $url = filter_var($url, FILTER_SANITIZE_URL);
    if(!filter_var($url, FILTER_VALIDATE_URL) === false){
        echo '<a href="'.$url.'">'.$url.'</a> : '.$li.' <br />';
    }
}
?>

第一部分效果很好,但我尝试添加描述的所有内容都失败了。

【问题讨论】:

标签: php dom text html-lists


【解决方案1】:

这是一个根据当前标记的简单示例:

$dom = new DOMDocument();
@$dom->loadHTML($urlContent);
$xpath = new DOMXPath($dom);
$lis = $xpath->evaluate("/html/body/li");

foreach ($lis as $li) {
    $a = $xpath->evaluate("span/a", $li)->item(0);
    $url = $a->getAttribute('href');
    var_dump($url, $a->nextSibling->nodeValue);
}

这里nextSibling 是文本内容,它跟在&lt;a&gt; 标记之后,所以nextSibling-&gt;nodeValue 将是" : Description",你必须删除空格和:,例如trim

工作fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2015-06-08
    • 2017-03-28
    • 2023-03-31
    • 2018-06-18
    • 2016-06-18
    • 1970-01-01
    相关资源
    最近更新 更多