我只需要检索维基百科页面的第一段。
内容必须是 HTML 格式,准备好在我的网站上显示(所以没有 BBCode或Wikipedia特殊代码!)
我只需要检索维基百科页面的第一段。
内容必须是 HTML 格式,准备好在我的网站上显示(所以没有 BBCode或Wikipedia特殊代码!)
有一种方法可以在不进行任何 HTML 解析的情况下获取整个“介绍部分”!与带有附加参数的 AnthonyS 的答案类似explaintext
,您可以获得纯文本的介绍部分文本。
以纯文本形式获取 Stack Overflow 的介绍:
使用页面标题:
或使用pageids
:
(警告已删除)
{
"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."
}
}
}
}
实际上有一个非常好的props叫做extracts,它可以用于专门为此目的设计的查询。
提取允许您获取文章摘录(截断的文章文本)。有一个名为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 年以来,Wikipedia 提供了具有更好缓存的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,您可以使用(例如, )设置CORS标头。&origin=
&origin=*
截至 2019 年:API 似乎返回了有关该页面的更多有用信息。
此代码允许您以纯文本形式检索页面第一段的内容。
这个答案的一部分来自这里,因此来自这里。有关更多信息,请参阅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,如果您使用其中一个可能会更好。
这是我现在正在为我正在制作的网站使用的代码,它需要获取维基百科文章的前导段落、摘要和第 0 节,并且这一切都在浏览器(客户端 JavaScript)中完成,这要归功于JSONP的魔力!--> http://jsfiddle.net/gatamadude/HMJJg/1/
它使用 Wikipedia API 来获取 HTML 中的前导段落(称为第 0 节),如下所示:http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Stack_Overflow&prop=text§ion=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
}
});
此 URL 将以 XML 格式返回摘要。
http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=Agra&MaxHits=1
我创建了一个函数来从 Wikipedia 获取关键字的描述。
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获取诸如第一段之类的内容,DBPedia获取 Wikipedia 内容并从中创建结构化信息 ( RDF ),并通过 API 使其可用。DBPedia API 是一个 SPARQL API(基于 RDF),但它输出 JSON 并且很容易包装。
作为示例,这里有一个名为WikipediaJS的超级简单的 JavaScript 库,它可以提取结构化内容,包括摘要第一段。
您可以在这篇博文中了解更多信息:WikipediaJS - 通过 Javascript 访问 Wikipedia 文章数据
JavaScript 库代码可以在wikipedia.js中找到。
abstract.xml.gz
转储听起来像你想要的。
如果您只是在寻找可以拆分的文本,但不想使用 API,请查看en.wikipedia.org/w/index.php?title=Elephant&action=raw。
我尝试了 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
这边走:
但是我们必须对搜索的大小写保持谨慎。
我的方法如下(在 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
可能需要进一步清洁,但基本上就是这样。