我只需要检索Wikipedia页面的第一段。内容必须为html格式,可以在我的网站上显示(因此,没有BBCODE或WIKIPEDIA特殊代码!)
我只需要检索Wikipedia页面的第一段。内容必须为html格式,可以在我的网站上显示(因此,没有BBCODE或WIKIPEDIA特殊代码!)
Answers:
有一种无需任何html解析即可获取整个“简介”的方法!与AnthonyS的答案类似,带有一个额外的explaintext
参数,您可以以纯文本形式获得介绍部分的文本。
以纯文本格式获取Stack Overflow的简介:
(警告已删除)
{
"query": {
"pages": {
"21721040": {
"pageid": 21721040,
"ns": 0,
"title": "Stack Overflow",
"extract": "Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky, as a more open alternative to earlier Q&A sites such as Experts Exchange. The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.\nIt features questions and answers on a wide range of topics in computer programming. The website serves as a platform for users to ask and answer questions, and, through membership and active participation, to vote questions and answers up or down and edit questions and answers in a fashion similar to a wiki or Digg. Users of Stack Overflow can earn reputation points and \"badges\"; for example, a person is awarded 10 reputation points for receiving an \"up\" vote on an answer given to a question, and can receive badges for their valued contributions, which represents a kind of gamification of the traditional Q&A site or forum. All user-generated content is licensed under a Creative Commons Attribute-ShareAlike license. Questions are closed in order to allow low quality questions to improve. Jeff Atwood stated in 2010 that duplicate questions are not seen as a problem but rather they constitute an advantage if such additional questions drive extra traffic to the site by multiplying relevant keyword hits in search engines.\nAs of April 2014, Stack Overflow has over 2,700,000 registered users and more than 7,100,000 questions. Based on the type of tags assigned to questions, the top eight most discussed topics on the site are: Java, JavaScript, C#, PHP, Android, jQuery, Python and HTML."
}
}
}
}
文档:API:query / prop = extracts
编辑:&redirects=1
按注释中的建议添加。
$extract = current((array)$data->query->pages)->extract;
。但是“注意:试图获取非对象的属性”的情况不断出现。
实际上,有一个非常不错的道具称为提取,可用于专门为此目的设计的查询。摘录允许您获取文章摘录(截断的文章文本)。有一个名为exintro的参数,可用于检索第零部分的文本(没有其他资源,如图像或信息框)。您还可以检索具有更细粒度的摘录,例如按一定数量的字符(exchars)或按一定数量的句子(exsentences)
这是一个示例查询 http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow 和API沙箱 http://en.wikipedia.org/wiki/特殊:ApiSandbox#action = query&prop = extracts&format = json&exintro =&titles = Stack%20Overflow可以对此查询进行更多实验。
请注意,如果您想要第一段,则仍然需要按照所选答案中的建议进行一些额外的解析。此处的区别在于,此查询返回的响应比建议的其他一些API查询短,这是因为api响应中没有其他要解析的资产,例如图像。
自2017年以来,维基百科提供了具有更好缓存的REST API。在文档中,您可以找到以下适合您的用例的API。(如新的“ 页面预览”功能所使用)
https://en.wikipedia.org/api/rest_v1/page/summary/Stack_Overflow
返回以下数据,这些数据可用于显示带有小缩略图的小图标:
{
"type": "standard",
"title": "Stack Overflow",
"displaytitle": "Stack Overflow",
"extract": "Stack Overflow is a question and answer site for professional and enthusiast programmers. It is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange. The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.",
"extract_html": "<p><b>Stack Overflow</b> is a question and answer site for professional and enthusiast programmers. It is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange. The name for the website was chosen by voting in April 2008 by readers of <i>Coding Horror</i>, Atwood's popular programming blog.</p>",
"namespace": {
"id": 0,
"text": ""
},
"wikibase_item": "Q549037",
"titles": {
"canonical": "Stack_Overflow",
"normalized": "Stack Overflow",
"display": "Stack Overflow"
},
"pageid": 21721040,
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/en/thumb/f/fa/Stack_Overflow_homepage%2C_Feb_2017.png/320px-Stack_Overflow_homepage%2C_Feb_2017.png",
"width": 320,
"height": 149
},
"originalimage": {
"source": "https://upload.wikimedia.org/wikipedia/en/f/fa/Stack_Overflow_homepage%2C_Feb_2017.png",
"width": 462,
"height": 215
},
"lang": "en",
"dir": "ltr",
"revision": "902900099",
"tid": "1a9cdbc0-949b-11e9-bf92-7cc0de1b4f72",
"timestamp": "2019-06-22T03:09:01Z",
"description": "website hosting questions and answers on a wide range of topics in computer programming",
"content_urls": {
"desktop": {
"page": "https://en.wikipedia.org/wiki/Stack_Overflow",
"revisions": "https://en.wikipedia.org/wiki/Stack_Overflow?action=history",
"edit": "https://en.wikipedia.org/wiki/Stack_Overflow?action=edit",
"talk": "https://en.wikipedia.org/wiki/Talk:Stack_Overflow"
},
"mobile": {
"page": "https://en.m.wikipedia.org/wiki/Stack_Overflow",
"revisions": "https://en.m.wikipedia.org/wiki/Special:History/Stack_Overflow",
"edit": "https://en.m.wikipedia.org/wiki/Stack_Overflow?action=edit",
"talk": "https://en.m.wikipedia.org/wiki/Talk:Stack_Overflow"
}
},
"api_urls": {
"summary": "https://en.wikipedia.org/api/rest_v1/page/summary/Stack_Overflow",
"metadata": "https://en.wikipedia.org/api/rest_v1/page/metadata/Stack_Overflow",
"references": "https://en.wikipedia.org/api/rest_v1/page/references/Stack_Overflow",
"media": "https://en.wikipedia.org/api/rest_v1/page/media/Stack_Overflow",
"edit_html": "https://en.wikipedia.org/api/rest_v1/page/html/Stack_Overflow",
"talk_page_html": "https://en.wikipedia.org/api/rest_v1/page/html/Talk:Stack_Overflow"
}
}
默认情况下,它遵循重定向(这样/api/rest_v1/page/summary/StackOverflow
也可以),但是可以通过以下方式禁用?redirect=false
如果您需要从其他域访问API,则可以使用&origin=
(例如&origin=*
)设置CORS标头
2019年更新:API似乎返回了有关页面的更多有用信息。
"other_tags" : "\"addr:country\"=>\"CW\",\"historic\"=>\"ruins\",\"name:nl\"=>\"Riffort\",\"wikidata\"=>\"Q4563360\",\"wikipedia\"=>\"nl:Riffort\""
提取了一些json数据,看起来 我们现在可以通过QID提取数据了吗?
此代码使您可以用纯文本检索页面第一段的内容。
这个答案的一部分来自这里,因此也来自这里。有关更多信息,请参见MediaWiki API文档。
// action=parse: get parsed text
// page=Baseball: from the page Baseball
// format=json: in json format
// prop=text: send the text content of the article
// section=0: top content of the page
$url = 'http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Baseball&prop=text§ion=0';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, "TestScript"); // required by wikipedia.org server; use YOUR user agent with YOUR contact information. (otherwise your IP might get blocked)
$c = curl_exec($ch);
$json = json_decode($c);
$content = $json->{'parse'}->{'text'}->{'*'}; // get the main text content of the query (it's parsed HTML)
// pattern for first match of a paragraph
$pattern = '#<p>(.*)</p>#Us'; // http://www.phpbuilder.com/board/showthread.php?t=10352690
if(preg_match($pattern, $content, $matches))
{
// print $matches[0]; // content of the first paragraph (including wrapping <p> tag)
print strip_tags($matches[1]); // Content of the first paragraph without the HTML tags.
}
就在这里。例如,如果您想获取文章Stack Overflow的第一部分的内容,请使用如下查询:
这些部分意味着:
format=xml
:以XML格式返回结果格式器。其他选项(如JSON)可用。这不会影响页面内容本身的格式,只会影响封闭的数据格式。
action=query&prop=revisions
:获取有关页面修订的信息。由于我们没有指定哪个版本,因此使用最新版本。
titles=Stack%20Overflow
:获取有关页面的信息Stack Overflow
。如果用分隔各个页面的名称,则可以一次性获得更多页面的文本|
。
rvprop=content
:返回修订的内容(或文本)。
rvsection=0
:仅返回第0部分的内容。
rvparse
:返回解析为HTML的内容。
请记住,这将返回第一部分的整个内容,包括帽子注释(“用于其他用途……”),信息框或图像。
有几种库可用于各种语言,使使用API变得更加容易,如果您使用其中一种库,可能会更好。
&redirects=true
到链接的末尾可确保您找到目标文章(如果有)。
这是我现在正在制作的网站上使用的代码,需要获取Wikipedia文章的开头段落/摘要/第0部分,这一切都在magick的帮助下在浏览器(客户端javascript)中完成JSONP!-> http://jsfiddle.net/gautamadude/HMJJg/1/
它使用Wikipedia API来获取HTML的开头段落(称为第0节),如下所示:http : //en.wikipedia.org/w/api.php?format=json&action=parse&page=Stack_Overflow&prop=text& section=0& callback=?
然后,它会剥离HTML和其他不需要的数据,为您提供文章摘要的干净字符串,如果需要的话,您可以稍作调整,在前几个段落周围添加一个“ p” html标记,但是现在只有一个换行符他们之间的性格。
码:
var url = "http://en.wikipedia.org/wiki/Stack_Overflow";
var title = url.split("/").slice(4).join("/");
//Get Leading paragraphs (section 0)
$.getJSON("http://en.wikipedia.org/w/api.php?format=json&action=parse&page=" + title + "&prop=text§ion=0&callback=?", function (data) {
for (text in data.parse.text) {
var text = data.parse.text[text].split("<p>");
var pText = "";
for (p in text) {
//Remove html comment
text[p] = text[p].split("<!--");
if (text[p].length > 1) {
text[p][0] = text[p][0].split(/\r\n|\r|\n/);
text[p][0] = text[p][0][0];
text[p][0] += "</p> ";
}
text[p] = text[p][0];
//Construct a string from paragraphs
if (text[p].indexOf("</p>") == text[p].length - 5) {
var htmlStrip = text[p].replace(/<(?:.|\n)*?>/gm, '') //Remove HTML
var splitNewline = htmlStrip.split(/\r\n|\r|\n/); //Split on newlines
for (newline in splitNewline) {
if (splitNewline[newline].substring(0, 11) != "Cite error:") {
pText += splitNewline[newline];
pText += "\n";
}
}
}
}
pText = pText.substring(0, pText.length - 2); //Remove extra newline
pText = pText.replace(/\[\d+\]/g, ""); //Remove reference tags (e.x. [1], [4], etc)
document.getElementById('textarea').value = pText
document.getElementById('div_text').textContent = pText
}
});
该网址将以xml格式返回摘要。
http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=Agra&MaxHits=1
我创建了一个从维基百科获取关键字描述的函数。
function getDescription($keyword){
$url='http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString='.urlencode($keyword).'&MaxHits=1';
$xml=simplexml_load_file($url);
return $xml->Result->Description;
}
echo getDescription('agra');
您还可以通过DBPedia获取内容,例如第一个pagagraph,该内容接受Wikipedia内容并从中创建结构化信息(RDF),并通过API使其可用。DBPedia API是一种SPARQL(基于RDF),但是它输出JSON,并且包装起来非常容易。
例如,这里有一个名为WikipediaJS的超简单JS库,它可以提取结构化的内容,包括摘要的第一段: http //okfnlabs.org/wikipediajs/
您可以在此博客文章中阅读有关它的更多信息: http //okfnlabs.org/blog/2012/09/10/wikipediajs-a-javascript-library-for-accessing-wikipedia-article-information.html
JS库代码可以在以下位置找到:https : //github.com/okfn/wikipediajs/blob/master/wikipedia.js
abstract.xml.gz
转储听起来像您想要的转储。
如果您只是在寻找可以拆分的文本,但又不想使用该API,请访问en.wikipedia.org/w/index.php?title=Elephant&action=raw
我的方法如下(在PHP中):
$url = "whatever_you_need"
$html = file_get_contents('https://en.wikipedia.org/w/api.php?action=opensearch&search='.$url);
$utf8html = html_entity_decode(preg_replace("/U\+([0-9A-F]{4})/", "&#x\\1;", $html), ENT_NOQUOTES, 'UTF-8');
$utf8html
可能需要进一步清洁,但仅此而已。
我尝试了@Michael Rapadas和@Krinkle的解决方案,但就我而言,我很难找到一些取决于大小写的文章。像这儿:
注意我截断了响应 exsentences=1
显然“标题标准化”无法正常工作:
标题规范化将页面标题转换为其规范形式。这意味着大写第一个字符,用空格替换下划线,并将名称空间更改为为该Wiki定义的本地化形式。无论使用哪个查询模块,标题归一化都是自动完成的。但是,页面标题(\ n)中的任何换行符都会引起奇怪的现象,应首先删除它们。
我知道我可以很容易地解决大小写问题,但也有将对象强制转换为数组的不便之处。
因此,因为我真的很想进行众所周知的定义搜索的第一段(不要冒险从其他文章中获取信息),所以我这样做是:
https://en.wikipedia.org/w/api.php?action=opensearch&search=led%20zeppelin&limit=1&format=json
请注意在这种情况下我做了截断 limit=1
这条路:
但是我们必须对搜索的大小写保持谨慎。
更多信息:https : //www.mediawiki.org/wiki/API : Opensearch