在 DOM XPath 中获取数据属性链接的文本值

布赖恩布鲁曼

我尝试了许多 xpath 表达式、评估、循环等。我得到的最好的是输出

" } object(DOMNodeList)#3 (1) { ["length"]=> int(0) }

有人告诉我我做错了什么,让我摆脱了痛苦。

$doc = new DOMDocument;
libxml_use_internal_errors(true);
$doc->preserveWhiteSpace = false;
$doc->strictErrorChecking = false;
$doc->recover = true;
$text = urlencode('dog show');
$html = file_get_contents('https://en.wikipedia.org/w/index.php?search=' . $text . '&title=Special:Search&fulltext=Search');
$doc->loadHTML(htmlspecialchars($html));

var_dump($doc);

把一切都带回来,没有问题——

在此处输入图片说明

现在,如何将第一个搜索结果作为 a href 的文本值/wiki/Dog_show以及title嵌入在节点列表中的the或 span 值返回?

我已经尝试定位data-serp-pos="0"包含我正在寻找的数据属性

$query = "//a/@href[data-serp-pos=\"0\"]";
$v = $xpath->evaluate($query);
var_dump($v);

我什至尝试在 DOM 树上更进一步

// $query = '//*[@id="mw-content-text"]/div/ul/li[1]/div[1]/a';
// $query = '//*[@id="mw-content-text"]/div/ul/li[1]';
// $query = '//div[@id="mw-content-text"]//a/@href';

尝试循环

// $result = '';
// foreach ($xpath->evaluate($query) as $p) {
//   $result .= $dom->saveHtml($p);
// }
// var_dump($result);

加入string在评价中,->nodeValue->item(0)等。

长度始终为 0。

整个DIV html如下...

<div class="mw-search-result-heading"><a href="/wiki/Dog_show" title="Dog show" data-serp-pos="0"><span class="searchmatch">Dog</span><span class="searchmatch">show</span></a></div>

什么(可能是简单的)解决方案我没有做来获取href值和关联的链接文本(或标题属性 - 在这种情况下是相同的)

阿布罗修斯教授

我经常发现使用 Chrome 中的开发人员工具“检查”我希望定位的元素最容易,从那里可以复制针对该特定节点的 XPath 表达式。这并不总是返回最有用的 XPath 表达式,但它通常是一个很好的起点 - 在这种情况下,我调整了返回的查询并添加到类名中。

希望能帮助到你

$term='dog show';
$url=sprintf('https://en.wikipedia.org/w/index.php?search=%s&title=Special:Search&fulltext=Search', urlencode( $term ) );


printf( '<a href="%s" target="_blank">%s</a>', $url, $url );

libxml_use_internal_errors(true);
$dom=new DOMDocument;
$dom->recover=true;
$dom->formatOutput=true;
$dom->preserveWhiteSpace=true;
$dom->strictErrorChecking=false;

$dom->loadHTMLFile( $url );
$xp=new DOMXPath( $dom );

/* possibly the important bit */
$query='//*[@id="mw-content-text"]/div/ul/li/div[@class="mw-search-result-heading"]/a';

$col=$xp->query( $query );

$html=array();

if( $col && $col->length > 0 ){
    foreach( $col as $node ){
        $html[]=array(
            'title'=>$node->nodeValue,
            'href'=>$node->getAttribute('href')
        );
    }
}


printf('<pre>%s</pre>',print_r($html,true));

将输出:

https://en.wikipedia.org/w/index.php?search=dog+show&title=Special:Search&fulltext=Search
Array(
[0] => Array
    (
        [title] => Dog show
        [href] => /wiki/Dog_show
    )

[1] => Array
    (
        [title] => Show dog
        [href] => /wiki/Show_dog
    )

[2] => Array
    (
        [title] => Westminster Kennel Club Dog Show
        [href] => /wiki/Westminster_Kennel_Club_Dog_Show
    )

[3] => Array
    (
        [title] => Dog Eat Dog (U.S. game show)
        [href] => /wiki/Dog_Eat_Dog_(U.S._game_show)
    )

   .......... etc

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章