我经常发现使用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