外部网站的PHP爬网特定选项卡的内容并返回href

问题描述 投票:0回答:1

使用PHP,我想在外部网站中检索特定元素。

外部网站为https://mcnmedia.tv/iframe/2684,我要检索的特定元素是“记录”选项卡中的第一链接

例如,第一个链接包含以下html;

<div class="small-12 medium-6 me column recording-item">
    <div class="recording-item-inner">
        <a class="small-12 column recording-name" href="/recordings/2435">
        <div class="info">
            <b>Mass</b><br>
            <small>26 Mar 2020</small>
        </div><i class="fa fa-play"></i></a>
    </div>
</div>

我想检索href并在我的网站上显示直接链接,例如;

View Latest Recording - https://mcnmedia.tv/recordings/2435

[我有以下PHP,但是它无法按照我的意愿工作,目前它仅输出文本(Mass 26 Mar 2020),我不确定如何获取实际的href链接地址?

<?php
$page = file_get_contents('https://mcnmedia.tv/iframe/2684');
@$doc = new DOMDocument();
@$doc->loadHTML($page);   
$xpath = new DomXPath($doc);
$nodeList = $xpath->query("//div[@class='recording-item-inner']");
$node = $nodeList->item(0);
// To check the result:
echo "<p>" . $node->nodeValue . "</p>";
?>

我该如何实现?

php html web-scraping file-get-contents
1个回答
0
投票

您对XPath的了解还不够,无法获取href,您可以添加/a/@href表示使用href标记内的<a>属性...

$nodeList = $xpath->evaluate("//div[@class='recording-item-inner']/a/@href");

您可以简化此过程,使用evaluate()来获取特定值,并将XPath修改为以字符串而不是节点的形式获取属性...

$href = $xpath->evaluate("string(//div[@class='recording-item-inner']/a/@href)");
echo "<p>" . $href . "</p>";
© www.soinside.com 2019 - 2024. All rights reserved.