我是否可以通过使用API访问任何维基百科页面的缩略图?我指的是方框右上方的图像。有什么api吗?
您可以使用prop=pageimages
获得任何维基百科页面的缩略图。例如:
http://en.wikipedia.org/w/api.php?action=query&titles=Al-Farabi&prop=pageimages&format=json&pithumbsize=100
你会得到缩略图的完整URL。
看prop=images
返回被解析页面中使用的图像文件名数组。然后你可以选择调用另一个API来查找完整的图像URL,例如:action=query&titles=Image:INSERT_EXAMPLE_FILE_NAME_HERE.jpg&prop=imageinfo&iiprop=url
或通过文件名的哈希值计算URL。
不幸的是,虽然prop=images
返回的图像数组是按照它们在页面上找到的顺序排列的,但不能保证第一个是信息框中的图像,因为有时页面会在信息框之前包含一个图像(大多数时候是关于页面元数据的图标:例如;"此文已锁定")。
在图像数组中搜索包含页面标题的第一个图像可能是对信息框图像的最佳猜测。
这是获取维基百科页面主图片的好方法
http://en.wikipedia.org/w/api.php?action=query∝pageimages&format=json&piprop=original&titles=India
查看MediaWiki API示例,获取维基百科页面的主图片:https://www.mediawiki.org/wiki/API:Page_info_in_search_results.
正如其他人所提到的,您将在API查询中使用prop=pageimages
。
如果你还想要图像描述,你可以在API查询中使用prop=pageimages|pageterms
。
您可以使用piprop=original
获取原始图像。或者您可以获得具有指定宽度/高度的缩略图图像。对于宽度/高度=600的缩略图,piprop=thumbnail&pithumbsize=600
。如果省略其中任何一个,API回调中返回的图像将默认为宽度/高度为50px的缩略图。
如果您请求JSON格式的结果,您应该始终在API查询中使用formatversion=2
(即format=json&formatversion=2
),因为它使从查询中检索图像更容易。
原图:
https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&prop=pageimages|pageterms&piprop=original&titles=Albert Einstein
缩略图大小(600px宽/高)图片:
https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&prop=pageimages|pageterms&piprop=thumbnail&pithumbsize=600&titles=Albert Einstein
方法1:您可以尝试这样的查询:
在响应中,您可以看到http://en.wikipedia.org/w/api.php?action=opensearch&限制= 5,格式= xml&搜索= italy&名称空间= 0
Image
标记。
<Item>
<Text xml:space="preserve">Italy national rugby union team</Text>
<Description xml:space="preserve">
The Italy national rugby union team represent the nation of Italy in the sport of rugby union.
</Description>
<Url xml:space="preserve">
http://en.wikipedia.org/wiki/Italy_national_rugby_union_team
</Url>
<Image source="http://upload.wikimedia.org/wikipedia/en/thumb/4/46/Italy_rugby.png/43px-Italy_rugby.png" width="43" height="50"/>
</Item>
方式二:使用query http://en.wikipedia.org/w/index.php?action=render&title=italy
,然后你可以得到一个原始的html代码,你可以得到图像使用类似PHP Simple HTML DOM Parser
http://simplehtmldom.sourceforge.net
很抱歉没有具体回答您关于主图像的问题。但这里有一些代码来获取所有图像的列表:
function makeCall($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
return curl_exec($curl);
}
function wikipediaImageUrls($url) {
$imageUrls = array();
$pathComponents = explode('/', parse_url($url, PHP_URL_PATH));
$pageTitle = array_pop($pathComponents);
$imagesQuery = "http://en.wikipedia.org/w/api.php?action=query&titles={$pageTitle}&prop=images&format=json";
$jsonResponse = makeCall($imagesQuery);
$response = json_decode($jsonResponse, true);
$imagesKey = key($response['query']['pages']);
foreach($response['query']['pages'][$imagesKey]['images'] as $imageArray) {
if($imageArray['title'] != 'File:Commons-logo.svg' && $imageArray['title'] != 'File:P vip.svg') {
$title = str_replace('File:', '', $imageArray['title']);
$title = str_replace(' ', '_', $title);
$imageUrlQuery = "http://en.wikipedia.org/w/api.php?action=query&titles=Image:{$title}&prop=imageinfo&iiprop=url&format=json";
$jsonUrlQuery = makeCall($imageUrlQuery);
$urlResponse = json_decode($jsonUrlQuery, true);
$imageKey = key($urlResponse['query']['pages']);
$imageUrls[] = $urlResponse['query']['pages'][$imageKey]['imageinfo'][0]['url'];
}
}
return $imageUrls;
}
print_r(wikipediaImageUrls('http://en.wikipedia.org/wiki/Saturn_%28mythology%29'));
print_r(wikipediaImageUrls('http://en.wikipedia.org/wiki/Hans-Ulrich_Rudel'));
我得到了这个http://en.wikipedia.org/wiki/Saturn_%28mythology%29:
Array
(
[0] => http://upload.wikimedia.org/wikipedia/commons/1/10/Arch_of_SeptimiusSeverus.jpg
[1] => http://upload.wikimedia.org/wikipedia/commons/8/81/Ivan_Akimov_Saturn_.jpg
[2] => http://upload.wikimedia.org/wikipedia/commons/d/d7/Lucius_Appuleius_Saturninus.jpg
[3] => http://upload.wikimedia.org/wikipedia/commons/2/2c/Polidoro_da_Caravaggio_-_Saturnus-thumb.jpg
[4] => http://upload.wikimedia.org/wikipedia/commons/b/bd/Porta_Maggiore_Alatri.jpg
[5] => http://upload.wikimedia.org/wikipedia/commons/6/6a/She-wolf_suckles_Romulus_and_Remus.jpg
[6] => http://upload.wikimedia.org/wikipedia/commons/4/45/Throne_of_Saturn_Louvre_Ma1662.jpg
)
第二个URL (http://en.wikipedia.org/wiki/Hans-Ulrich_Rudel):
)Array
(
[0] => http://upload.wikimedia.org/wikipedia/commons/e/e9/BmRKEL.jpg
[1] => http://upload.wikimedia.org/wikipedia/commons/3/3f/BmRKELS.jpg
[2] => http://upload.wikimedia.org/wikipedia/commons/2/2c/Bundesarchiv_Bild_101I-655-5976-04%2C_Russland%2C_Sturzkampfbomber_Junkers_Ju_87_G.jpg
[3] => http://upload.wikimedia.org/wikipedia/commons/6/62/Bundeswehr_Kreuz_Black.svg
[4] => http://upload.wikimedia.org/wikipedia/commons/9/99/Flag_of_German_Reich_%281935%E2%80%931945%29.svg
[5] => http://upload.wikimedia.org/wikipedia/en/6/64/HansUlrichRudel.jpeg
[6] => http://upload.wikimedia.org/wikipedia/commons/8/82/Heinkel_He_111_during_the_Battle_of_Britain.jpg
[7] => http://upload.wikimedia.org/wikipedia/commons/6/66/Regulation_WW_II_Underwing_Balkenkreuz.png
)
注意,URL在第二个数组的第6个元素上改变了一位。这就是@JosephJaber在上面的评论中警告的。
希望这能帮助到别人。
我写了一些代码,通过维基百科文章标题获得主图像(完整URL)。它不是完美的,但总的来说,我对结果很满意。
挑战在于,当查询特定标题时,Wikipedia返回多个图像文件名(没有路径)。此外,二次搜索(我使用了本线程中发布的代码varatis -谢谢!)返回基于搜索的图像文件名找到的所有图像的url,而不考虑原始文章标题。在这一切之后,我们可能会得到一个与搜索无关的通用图像,因此我们将其过滤掉。代码遍历文件名和url,直到找到(希望是最好的)匹配。有点复杂,但它可以工作:)
关于通用过滤器的注意:我一直在为isGeneric()函数编译通用图像字符串列表,但该列表不断增长。我正在考虑把它作为一个公共列表,如果有任何兴趣请告诉我。
Pre:
protected static $baseurl = "http://en.wikipedia.org/w/api.php";
主函数-从标题中获取图像URL:
public static function getImageURL($title)
{
$images = self::getImageFilenameObj($title); // returns JSON object
if (!$images) return '';
foreach ($images as $image)
{
// get object of image URL for given filename
$imgjson = self::getFileURLObj($image->title);
// return first image match
foreach ($imgjson as $img)
{
// get URL for image
$url = $img->imageinfo[0]->url;
// no image found
if (!$url) continue;
// filter generic images
if (self::isGeneric($url)) continue;
// match found
return $url;
}
}
// match not found
return '';
}
==下面的函数由上面的main函数调用==
按标题获取JSON对象(文件名):
public static function getImageFilenameObj($title)
{
try // see if page has images
{
// get image file name
$json = json_decode(
self::retrieveInfo(
self::$baseurl . '?action=query&titles=' .
urlencode($title) . '&prop=images&format=json'
))->query->pages;
/** The foreach is only to get around
* the fact that we don't have the id.
*/
foreach ($json as $id) { return $id->images; }
}
catch(exception $e) // no images
{
return NULL;
}
}
通过文件名获取JSON对象(url):
public static function getFileURLObj($filename)
{
try // resolve URL from filename
{
return json_decode(
self::retrieveInfo(
self::$baseurl . '?action=query&titles=' .
urlencode($filename) . '&prop=imageinfo&iiprop=url&format=json'
))->query->pages;
}
catch(exception $e) // no URLs
{
return NULL;
}
}
过滤掉一般图片:
public static function isGeneric($url)
{
$generic_strings = array(
'_gray.svg',
'icon',
'Commons-logo.svg',
'Ambox',
'Text_document_with_red_question_mark.svg',
'Question_book-new.svg',
'Canadese_kano',
'Wiki_letter_',
'Edit-clear.svg',
'WPanthroponymy',
'Compass_rose_pale',
'Us-actor.svg',
'voting_box',
'Crystal_',
'transportation_inv',
'arrow.svg',
'Quill_and_ink-US.svg',
'Decrease2.svg',
'Rating-',
'template',
'Nuvola_apps_',
'Mergefrom.svg',
'Portal-',
'Translation_to_',
'/School.svg',
'arrow',
'Symbol_',
'stub',
'Unbalanced_scales.svg',
'-logo.',
'P_vip.svg',
'Books-aj.svg_aj_ashton_01.svg',
'Film',
'/Gnome-',
'cap.svg',
'Missing',
'silhouette',
'Star_empty.svg',
'Music_film_clapperboard.svg',
'IPA_Unicode',
'symbol',
'_highlighting_',
'pictogram',
'Red_pog.svg',
'_medal_with_cup',
'_balloon',
'Feature',
'Aiga_'
);
foreach ($generic_strings as $str)
{
if (stripos($url, $str) !== false) return true;
}
return false;
}
评论欢迎。
让我们以页面http://en.wikipedia.org/wiki/index.html?curid=57570为例获取主图片
Check out
道具= pageprops
action = query& pageids = 57570,支撑= pageprops&格式= json
结果页数据例如
{ "pages" : { "57570":{
"pageid":57570,
"ns":0,
"title":"Sachin Tendulkar",
"pageprops" : {
"defaultsort":"Tendulkar,Sachin",
"page_image":"Sachin_at_Castrol_Golden_Spanner_Awards_(crop).jpg",
"wikibase_item":"Q9488"
}
}
}
}}
我们得到主Pic文件名这个结果为
* * (wikiId) .pageprops。page_image = Sachin_at_Castrol_Golden_Spanner_Awards_(crop).jpg**
现在我们有了图像文件名,我们将不得不进行另一个Api调用来从文件名获取完整的图像路径,如下所示
action = query&标题=形象:INSERT_EXAMPLE_FILE_NAME_HERE.jpg&支持= imageinfo& iiprop url =
。
action = query&标题=形象:Sachin_at_Castrol_Golden_Spanner_Awards_(作物).jpg&支持= imageinfo& iiprop url =
返回包含url的图像数据数组http://upload.wikimedia.org/wikipedia/commons/3/35/Sachin_at_Castrol_Golden_Spanner_Awards_%28crop%29.jpg
我有一种方法可以可靠地获得维基百科页面的主图像-扩展名为PageImages
PageImages扩展收集关于页面上使用的图像的信息。
它的目的是返回一个最合适的缩略图对于一篇文章,试图只返回有意义的图像,例如没有那些来自维护模板、存根或标志图标。目前使用该页中使用的第一个非无意义图像。
https://www.mediawiki.org/wiki/Extension PageImages
只需添加道具页面图像到您的API查询:
/w/api.php?action=query&prop=pageimages&titles=Somepage&format=xml
这可靠地过滤掉恼人的默认图像,并防止你不得不过滤他们自己!扩展安装在所有主要的维基百科页面…
就像Anuraj提到的,pagerimages参数就是它。看看下面的url,它会带来一些漂亮的东西:
https://en.wikipedia.org/w/api.php?action=query&prop=info|extracts|pageimages|images&inprop=url&exsentences=1&titles=india
下面是一些有趣的参数:
- 两个参数提取和解释给您一个简短的您可以使用的描述。(句数是你想要在摘录中包含的句子的数量)
- info和inprop=url参数给出了页面的url
- prop属性有多个参数,用一个条形符号分隔 如果你在这里插入format=json就更好了
参见维基百科API上的相关问题。但是,我不知道是否可以通过API检索缩略图。
你也可以考虑只解析网页来找到图像的URL,并以这种方式检索图像。
以下是我为95%的文章找到的xpath列表。主要的是1、2、3和4。很多文章的格式都不正确,这些是例外情况:
可以使用DOM解析库来使用XPath获取图像。
static NSString *kWikipediaImageXPath2 = @"//*[@id='"mw-content-text'"]/div[1]/div/table/tr[2]/td/a/img";
static NSString *kWikipediaImageXPath3 = @"//*[@id='"mw-content-text'"]/div[1]/table/tr[1]/td/a/img";
static NSString *kWikipediaImageXPath1 = @"//*[@id='"mw-content-text'"]/div[1]/table/tr[2]/td/a/img";
static NSString *kWikipediaImageXPath4 = @"//*[@id='"mw-content-text'"]/div[2]/table/tr[2]/td/a/img";
static NSString *kWikipediaImageXPath5 = @"//*[@id='"mw-content-text'"]/div[1]/table/tr[2]/td/p/a/img";
static NSString *kWikipediaImageXPath6 = @"//*[@id='"mw-content-text'"]/div[1]/table/tr[2]/td/div/div/a/img";
static NSString *kWikipediaImageXPath7 = @"//*[@id='"mw-content-text'"]/div[1]/table/tr[1]/td/div/div/a/img";
我在libxml2.2周围使用了一个名为apple的ObjC包装器来提取图像url。希望对您有所帮助
您也可以使用名为SDWebImage的可可荚
代码示例(记住还要添加import SDWebImage
):
func requestInfo(flowerName: String) {
let parameters : [String:String] = [
"format" : "json",
"action" : "query",
"prop" : "extracts|pageimages",//pageimages allows fetch imagePath
"exintro" : "",
"explaintext" : "",
"titles" : flowerName,
"indexpageids" : "",
"redirects" : "1",
"pithumbsize" : "500"//specify image size in px
]
AF.request(wikipediaURL, method: .get, parameters: parameters).responseJSON { (response) in
switch response.result {
case .success(let value):
print("Got the wikipedia info.")
print(response)
let flowerJSON : JSON = JSON(response.value!)
let pageid = flowerJSON["query"]["pageids"][0].stringValue
let flowerDescription = flowerJSON["query"]["pages"][pageid]["extract"].stringValue
let flowerImageURL = flowerJSON["query"]["pages"][pageid]["thumbnail"]["source"].stringValue //fetching Image URL
self.wikiInfoLabel.text = flowerDescription
self.imageView.sd_setImage(with: URL(string : flowerImageURL))//imageView updated with Wiki Image
case .failure(let error):
print(error)
}
}
}
我认为不是,但您可以使用链接解析器捕获图像HTML文档