【问题标题】:How to extracting a sub <a> tags and prints them out如何提取子 <a> 标签并打印出来
【发布时间】:2016-12-09 19:12:47
【问题描述】:

我试图从&lt;div&gt; 元素内的子&lt;a&gt; 标记中提取链接。我已经使用 PHP 的 DOM 来解析 HTML 在此站点上的解释:[http://htmlparsing.com/php.html] [1]。我还使用 [Using PHP DOM document, to select HTML element by its class and get its text [2] 中的相关答案修改了代码,以使用类名选择元素。以下是 HTML 结构和 PHP 代码。但是,PHP 代码似乎不能正常工作,因为一旦到达第 11 个元素,它就会停止打印链接。

HTML 结构:

    <div class="avtar-abt">
    <h3 class="mb6"><a href="testingwebsite.com1"></i></a></h3>
    </div>

  <div class="avtar-abt">
    <h3 class="mb6"><a href="testingwebsite.com2"></i></a></h3>
    </div>

  <div class="avtar-abt">
    <h3 class="mb6"><a href="testingwebsite.com3"></i></a></h3>
    </div>

PHP 代码:

    # Create a DOM parser object
$dom = new DOMDocument();

# Parse the HTML from Google.
# The @ before the method call suppresses any warnings that
# loadHTML might throw because of invalid HTML in the page.
@$dom->loadHTML($html);
$xpath = new DOMXPath ($dom);

$classname = 'mb6';

foreach ($xpath->query("//*[@class='$classname']/a") as $link) {
    echo $link->getAttribute('href');
    echo "<br />";

}  

【问题讨论】:

标签: php html dom


【解决方案1】:

您不应该使用两个循环(顺便说一句,第一个的语法错误)。您可以使用 XPath 直接找到链接节点,方法是将 /a 添加到搜索路径:

foreach ($xpath->query("//*[@class='$classname']/a") as $link) {
    echo $link->getAttribute('href');
    echo "<br />";
}   

【讨论】:

  • 已经解决了。但是,它只会继续获取前 10 个链接并停止搜索
  • 你能发布一个没有找到第 11 个链接的 HTML 字符串吗?
猜你喜欢
  • 2020-08-24
  • 2012-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
相关资源
最近更新 更多