【问题标题】:Scraping href value from <a> tag using PHP使用 PHP 从 <a> 标记中抓取 href 值
【发布时间】:2016-04-06 22:42:06
【问题描述】:

我正在使用 simple_html_dom 从 HTML 标记中检索 href 属性值。我正在抓取的数据放在 HTML 表中。以下代码成功指向数据并显示为超链接。

// Include the library to use it.
include_once('simple_html_dom.php');

// Get the HTML from the file or website.
$html = file_get_html('source.html');

// Put all of the <a> tags into an array named $result
$result = $html -> find('table tbody tr td a');

// Run through the array using a foreach loop and print each link out using echo
foreach($result as $link) {
echo $link."<br/>";
}

但我需要标签中的 href 值,为此我遵循Retrieve multiple value of a <a href> tag using php 的解释并使用以下代码,但它再次搜索整个文档并提取位于表外的所有链接。我还用$result$link 替换了$html,但它没有显示任何内容。

preg_match_all("/href=\"(.*?)\"/i", $html, $matches);
print_r($matches);

如何使用上述方法之一从 HTML 表下的 href 属性获取值?该表没有任何类或 id 可在选择器中使用。

注意:我也调查过:Retrieve The link value form <a href> tag using php,但无法弄清楚。

【问题讨论】:

    标签: php web-scraping html-parsing


    【解决方案1】:

    我使用preg_match 代替preg_match_all,然后使用echo 代替打印。以下代码以第一个链接为目标并将其显示在屏幕上。

    preg_match("/href=\"(.*?)\"/i", $html, $matches);
    echo $matches;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 2010-10-27
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多