MediaWiki 是否提供了返回“背景信息”表中存在的信息的方法? (通常在文章页面的右侧)例如,我想从 Radiohead 获取 Origin:
http://en.wikipedia.org/wiki/Radiohead
或者我需要解析html页面吗?
最佳答案
您可以使用revisions
property与 rvgeneratexml 参数一起生成文章的解析树。然后您可以应用 XPath 或遍历它并查找所需的信息。
这是一个示例代码:
$page = 'Radiohead';
$api_call_url = 'http://en.wikipedia.org/w/api.php?action=query&titles=' .
urlencode( $page ) . '&prop=revisions&rvprop=content&rvgeneratexml=1&format=json';
您必须向 API 表明自己的身份,请参阅 Meta Wiki 了解更多信息.
$user_agent = 'Your name <your email>';
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => $user_agent,
CURLOPT_URL => $api_call_url,
) );
$response = json_decode( curl_exec( $curl ), true );
curl_close( $curl );
foreach( $response['query']['pages'] as $page ) {
$parsetree = simplexml_load_string( $page['revisions'][0]['parsetree'] );
这里我们使用 XPath 来查找 Infobox 音乐艺术家
的参数 Origin
及其值。请参阅XPath specification对于语法等。您也可以遍历树并手动查找节点。请随意研究解析树以更好地掌握它。
$infobox_origin = $parsetree->xpath( '//template[contains(string(title),' .
'"Infobox musical artist")]/part[contains(string(name),"Origin")]/value' );
echo trim( strval( $infobox_origin[0] ) );
}
关于api - 维基百科 API - 抓取 'Background Inforamtion' 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5909384/