【问题标题】:How to extract particular link from html page using php如何使用php从html页面中提取特定链接
【发布时间】:2021-11-30 07:15:50
【问题描述】:

嗨,我正在尝试使用正则表达式从标签中 scrape href 链接,但我无法检索链接,有人可以帮我实现这一点吗?这是我想从中提取的链接html页面。 /u/0/uc?export=download&confirm=EY_S&id=fileid这是我的php函数

<?php
function dwnload($url)
{
    $scriptx = "";
    $internalErrors = libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    @$dom->loadHTML(curl($url));
    foreach ($dom->getElementsByTagName('a') as $k => $js) {
        $scriptx .= $js->nodeValue;
    }
    preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $scriptx, $match);
    $vlink = "";
    foreach ($match[0] as $c) {
        if (strpos($c, 'export=download') !== false) {
            $vlink = $c;
        }
    }

    return $vlink; 
}?>

谢谢

【问题讨论】:

  • 我看到你的代码并且明白 $scriptx 是一个巨大的变量并且你想要正确的块......但是你正在循环 $match[0] 这应该是可能的......怎么样循环比赛...还有谁向你保证你得到的块是完整的 url?! -- 在运行之前打印您的响应值,例如 $c ... $match[0] 应该是字符串而不是数组。

标签: php regex


【解决方案1】:

您正在连接链接文本。那没有意义。如果您尝试提取链接,DOMNode::getElementsByTagName() 已经完成了这项工作。您只需要过滤结果。

让我们考虑一个小的 HTML 片段:

$html = <<<'HTML'
<a href="/u/0/uc?export=download&amp;confirm=EY_S&amp;id=fileid">SUCCESS</a>
<a href="/another/link">FAILURE</a>
HTML;

现在迭代 a 元素并通过它们的 href 属性过滤它们。

$document = new DOMDocument();
$document->loadHTML($html);

foreach ($document->getElementsByTagName('a') as $a) {
    $href = $a->getAttribute('href');
    if (strpos($href, 'export=download') !== false) {
        var_dump([$href, $a->textContent]);
    }
}

输出:

array(2) {
  [0]=>
  string(46) "/u/0/uc?export=download&confirm=EY_S&id=fileid"
  [1]=>
  string(7) "SUCCESS"
}

现在,如果这是一个字符串匹配,则可以使用 Xpath 表达式:

$document = new DOMDocument();
$document->loadHTML($html);
$xpath = new DOMXpath($document);

foreach ($xpath->evaluate('//a[contains(@href, "export=download")]') as $a) {
    var_dump([$a->getAttribute('href'), $a->textContent]);
}

或者将 Xpath 表达式与更具体的正则表达式结合起来:

$pattern = '((?:\\?|&)export=download(?:&|$))';
foreach ($xpath->evaluate('//a[contains(@href, "export=download")]') as $a) {
    $href = $a->getAttribute('href');
    if (preg_match($pattern, $href)) {
        var_dump([$href, $a->textContent]);
    }
}

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 2011-06-04
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多