Xpath php 获取链接

发布于 2024-09-10 19:06:48 字数 668 浏览 0 评论 0原文

我使用此示例从网站获取链接:

http: //www.merchantos.com/makebeta/php/scraping-links-with-php/

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

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    var_dump($href);
    $url = $href->getAttribute('href');
    echo "<br />Link stored: $url";
}

效果很好;获取所有链接;但我无法获得链接的实际“标题”;例如,如果我有:

<a href="www.google.com">Google</a>

我也希望能够获取“Google”术语。

我有点迷失,而且对 xpath 还很陌生。

I'm using this example to fetch links from a website :

http://www.merchantos.com/makebeta/php/scraping-links-with-php/

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

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    var_dump($href);
    $url = $href->getAttribute('href');
    echo "<br />Link stored: $url";
}

It works well; getting all the links; but I cannot get the actual 'title' of the link; for example if i have :

<a href="www.google.com">Google</a>

I want to be able to fetch 'Google' term too.

I'm little lost and quite new to xpath.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夕嗳→ 2024-09-17 19:06:48

您正在寻找“a”节点内的 Textnode 的“nodeValue”。
获得该值

$title = $href->firstChild->nodeValue;

您可以通过完整工作示例

<?php
$dom = DomDocument::loadHTML("<html><body><a href='www.test.de'>DONE</a></body></html>");

$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');
    $title = $href->firstChild->nodeValue;
    echo "<br />Link stored: $url $title";
}

:打印:

链接已存储:www.test.de 完成

You are looking for the "nodeValue" of the Textnode inside the "a" node.
You can get that value with

$title = $href->firstChild->nodeValue;

Full working example:

<?php
$dom = DomDocument::loadHTML("<html><body><a href='www.test.de'>DONE</a></body></html>");

$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');
    $title = $href->firstChild->nodeValue;
    echo "<br />Link stored: $url $title";
}

Prints:

Link stored: www.test.de DONE

眼眸里的那抹悲凉 2024-09-17 19:06:48

试试这个:

$link_title = $href->nodeValue;

Try this:

$link_title = $href->nodeValue;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文