API:Compare/es
![]() | Esta página es parte de la documentación de la API de acciones de MediaWiki. |
Solicitud GET para obtener la diferencia entre dos páginas.
Versión de MediaWiki: | ≥ 1.18 |
Documentación de la API
![]() | La siguiente documentación es la salida de Special: |
action=compare
- This module requires read rights.
- Source: MediaWiki
- License: GPL-2.0-or-later
Get the difference between two pages.
A revision number, a page title, a page ID, text, or a relative reference for both "from" and "to" must be passed.
- fromtitle
First title to compare.
- fromid
First page ID to compare.
- Type: integer
- fromrev
First revision to compare.
- Type: integer
- fromslots
Override content of the revision specified by fromtitle, fromid or fromrev.
This parameter specifies the slots that are to be modified. Use fromtext-{slot}, fromcontentmodel-{slot}, and fromcontentformat-{slot} to specify content for each slot.
- Values (separate with | or alternative): main
- fromtext-{slot}
Text of the specified slot. If omitted, the slot is removed from the revision.
- This is a templated parameter. When making the request, {slot} in the parameter's name should be replaced with values of fromslots.
- fromsection-{slot}
When fromtext-{slot} is the content of a single section, this is the section identifier. It will be merged into the revision specified by fromtitle, fromid or fromrev as if for a section edit.
- This is a templated parameter. When making the request, {slot} in the parameter's name should be replaced with values of fromslots.
- fromcontentformat-{slot}
Content serialization format of fromtext-{slot}.
- This is a templated parameter. When making the request, {slot} in the parameter's name should be replaced with values of fromslots.
- One of the following values: application/json, application/octet-stream, application/unknown, application/vue+xml, application/x-binary, text/css, text/javascript, text/plain, text/unknown, text/x-wiki, unknown/unknown
- fromcontentmodel-{slot}
Content model of fromtext-{slot}. If not supplied, it will be guessed based on the other parameters.
- This is a templated parameter. When making the request, {slot} in the parameter's name should be replaced with values of fromslots.
- One of the following values: GadgetDefinition, Json.JsonConfig, JsonSchema, MassMessageListContent, NewsletterContent, Scribunto, SecurePoll, css, flow-board, javascript, json, sanitized-css, text, translate-messagebundle, unknown, vue, wikitext
- frompst
Do a pre-save transform on fromtext-{slot}.
- Type: boolean (details)
- fromtext
- Deprecated.
Specify fromslots=main and use fromtext-main instead.
- fromcontentformat
- Deprecated.
Specify fromslots=main and use fromcontentformat-main instead.
- One of the following values: application/json, application/octet-stream, application/unknown, application/vue+xml, application/x-binary, text/css, text/javascript, text/plain, text/unknown, text/x-wiki, unknown/unknown
- fromcontentmodel
- Deprecated.
Specify fromslots=main and use fromcontentmodel-main instead.
- One of the following values: GadgetDefinition, Json.JsonConfig, JsonSchema, MassMessageListContent, NewsletterContent, Scribunto, SecurePoll, css, flow-board, javascript, json, sanitized-css, text, translate-messagebundle, unknown, vue, wikitext
- fromsection
- Deprecated.
Only use the specified section of the specified 'from' content.
- totitle
Second title to compare.
- toid
Second page ID to compare.
- Type: integer
- torev
Second revision to compare.
- Type: integer
- torelative
Use a revision relative to the revision determined from fromtitle, fromid or fromrev. All of the other 'to' options will be ignored.
- One of the following values: cur, next, prev
- toslots
Override content of the revision specified by totitle, toid or torev.
This parameter specifies the slots that are to be modified. Use totext-{slot}, tocontentmodel-{slot}, and tocontentformat-{slot} to specify content for each slot.
- Values (separate with | or alternative): main
- totext-{slot}
Text of the specified slot. If omitted, the slot is removed from the revision.
- This is a templated parameter. When making the request, {slot} in the parameter's name should be replaced with values of toslots.
- tosection-{slot}
When totext-{slot} is the content of a single section, this is the section identifier. It will be merged into the revision specified by totitle, toid or torev as if for a section edit.
- This is a templated parameter. When making the request, {slot} in the parameter's name should be replaced with values of toslots.
- tocontentformat-{slot}
Content serialization format of totext-{slot}.
- This is a templated parameter. When making the request, {slot} in the parameter's name should be replaced with values of toslots.
- One of the following values: application/json, application/octet-stream, application/unknown, application/vue+xml, application/x-binary, text/css, text/javascript, text/plain, text/unknown, text/x-wiki, unknown/unknown
- tocontentmodel-{slot}
Content model of totext-{slot}. If not supplied, it will be guessed based on the other parameters.
- This is a templated parameter. When making the request, {slot} in the parameter's name should be replaced with values of toslots.
- One of the following values: GadgetDefinition, Json.JsonConfig, JsonSchema, MassMessageListContent, NewsletterContent, Scribunto, SecurePoll, css, flow-board, javascript, json, sanitized-css, text, translate-messagebundle, unknown, vue, wikitext
- topst
Do a pre-save transform on totext.
- Type: boolean (details)
- totext
- Deprecated.
Specify toslots=main and use totext-main instead.
- tocontentformat
- Deprecated.
Specify toslots=main and use tocontentformat-main instead.
- One of the following values: application/json, application/octet-stream, application/unknown, application/vue+xml, application/x-binary, text/css, text/javascript, text/plain, text/unknown, text/x-wiki, unknown/unknown
- tocontentmodel
- Deprecated.
Specify toslots=main and use tocontentmodel-main instead.
- One of the following values: GadgetDefinition, Json.JsonConfig, JsonSchema, MassMessageListContent, NewsletterContent, Scribunto, SecurePoll, css, flow-board, javascript, json, sanitized-css, text, translate-messagebundle, unknown, vue, wikitext
- tosection
- Deprecated.
Only use the specified section of the specified 'to' content.
- prop
Which pieces of information to get.
- diff
- The diff HTML.
- diffsize
- The size of the diff HTML, in bytes.
- rel
- The revision IDs of the revision previous to 'from' and after 'to', if any.
- ids
- The page and revision IDs of the 'from' and 'to' revisions.
- title
- The page titles of the 'from' and 'to' revisions.
- user
- The username and ID of the 'from' and 'to' revisions. If the user has been revision deleted, a fromuserhidden or touserhidden property will be returned.
- comment
- The comment on the 'from' and 'to' revisions. If the comment has been revision deleted, a fromcommenthidden or tocommenthidden property will be returned.
- parsedcomment
- The parsed comment on the 'from' and 'to' revisions. If the comment has been revision deleted, a fromcommenthidden or tocommenthidden property will be returned.
- size
- The size of the 'from' and 'to' revisions.
- timestamp
- The timestamp of the 'from' and 'to' revisions.
- Values (separate with | or alternative): comment, diff, diffsize, ids, parsedcomment, rel, size, timestamp, title, user
- Default: diff|ids|title
- slots
Return individual diffs for these slots, rather than one combined diff for all slots.
- Values (separate with | or alternative): main
- To specify all values, use *.
- difftype
Return the comparison formatted as inline HTML.
- One of the following values: inline, table, unified
- Default: table
- Create a diff between revision 1 and 2.
- api.php?action=compare&fromrev=1&torev=2 [open in sandbox]
Ejemplo
Solicitud GET
Respuesta
{
"compare": {
"fromid": 1882196,
"fromrevid": 739666518,
"fromns": 10,
"fromtitle": "Template:Unsigned",
"toid": 32371774,
"torevid": 909784724,
"tons": 10,
"totitle": "Template:UnsignedIP",
...
}
}
Código de muestra
Python
#!/usr/bin/python3
"""
compare.py
MediaWiki Action API Code Samples
Demo of `Compare` module: Compare the current revisions of two different pages
MIT license
"""
import requests
S = requests.Session()
URL = "https://en.wikipedia.org/w/api.php"
PARAMS = {
'action':"compare",
'format':"json",
'fromtitle':'Template:Unsigned',
'totitle':'Template:UnsignedIP'
}
R = S.get(url=URL, params=PARAMS)
DATA = R.json()
print(DATA)
PHP
<?php
/*
compare.php
MediaWiki Action API Code Samples
Demo of `Compare` module: Compare the current revisions of two different pages
MIT license
*/
$endPoint = "https://en.wikipedia.org/w/api.php";
$params = [
"action" => "compare",
"format" => "json",
"fromtitle" => "Template:Unsigned",
"totitle" => "Template:UnsignedIP"
];
$url = $endPoint . "?" . http_build_query( $params );
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$output = curl_exec( $ch );
curl_close( $ch );
echo( $output );
JavaScript
/*
compare.js
MediaWiki Action API Code Samples
Demo of `Compare` module: Compare the current revisions of two different pages
MIT license
*/
var url = "https://en.wikipedia.org/w/api.php";
var params = {
action: "compare",
format: "json",
fromtitle: "Template:Unsigned",
totitle: "Template:UnsignedIP"
};
request.get({ url: url, qs: params }, function(error, res, body) {
if (error) {
return;
}
console.log(body);
});
MediaWiki JS
/*
compare.js
MediaWiki Action API Code Samples
Demo of `Compare` module: Compare the current revisions of two different pages
MIT license
*/
var params = {
action: "compare",
format: "json",
fromtitle: "Template:Unsigned",
totitle: "Template:UnsignedIP"
},
api = new mw.Api();
api.get( params ).done( function ( data ) {
console.log( data );
} );
Errores posibles
Código | Info |
---|---|
compare-relative-to-nothing | No 'from' revision for torelative to be relative to. |
compare-relative-to-deleted | Cannot use torelative=value relative to a deleted revision. |
missingrev-title | No current revision of title title. |
baddiff | La comparación no puede recuperarse. Una o ambas revisiones no existen o no tienes permiso para verlas. |
missingcontent-revid | Missing content for revision ID revid. |
invalidtitle | Título incorrecto "title". |
nosuchpageid | No hay ninguna página con identificador id. |
missingtitle-byname | La página name no existe. |
nosuchrevid | No hay ninguna revisión con identificador id. |
missingcontent-revid-role | Missing content for revision ID id for role main. |
compare-nosuchfromsection | No existe una sección name en el contenido 'from'. |
compare-nosuchtosection | No existe una sección name en el contenido 'to'. |
compare-maintextrequired | Parameter fromtext-main is required when fromslots contains main (cannot delete the main slot). |
compare-maintextrequired | Parameter totext-main is required when toslots contains main (cannot delete the main slot). |
compare-notext | No se puede usar el parámetro $1 sin $2. |
compare-no-title | Cannot pre-save transform without a title. Try specifying fromtitle or totitle. |
compare-nofromrevision | No 'from' revision. Specify fromrev, fromtitle, or fromid. |
compare-notorevision | No 'to' revision. Specify torev, totitle, or toid. |
sectionsnotsupported | Las secciones no son compatibles con el modelo de contenido model. |
sectionreplacefailed | No se ha podido combinar la sección actualizada. |
missingparam | Al menos uno de los parámetros fromtitle , fromid , fromrev , fromtext , fromrelative y fromslots es necesario. |
missingparam | Al menos uno de los parámetros totitle , toid , torev , totext , torelative y toslots es necesario. |
Historial de parámetros
- v1.32: Introducido
fromslots
,toslots
,fromtext-{slot}
,fromsection-{slot}
,fromcontentformat-{slot}
,fromcontentmodel-{slot}
,totext-{slot}
,tosection-{slot}
,tocontentformat-{slot}
,tocontentmodel-{slot}
- v1.30: Introducido
frompst
,torelative
,topst
,prop
- v1.20: Introducido
fromid
,toid
Notas adicionales
Para obtener la diferencia entre dos páginas, un número de revisión, un título de página o un ID de página para ambos from
y to
debe ser pasado.
Comparación relativa en primera y última revisión
- Puedes solicitar una comparación relativa a prev en la primera revisión de una página, esto dará como resultado que el texto completo de la primera revisión se devuelva como la diferencia. Ten en cuenta que esto no es exacto, ya que en algunos casos puede haber contenido predeterminado para la página antes de su primera revisión. La propiedad de
fromrevid
estará ausente de los resultados. - Del mismo modo, puedes solicitar la próxima comparación relativa en la última revisión de una página.
- (Nota: esta es la última revisión al momento de escribir este tema. Debido a que la página está protegida, probablemente no debería cambiar). El resultado es un diferencial vacío y los
torevid
estarán ausentes. A diferencia de la mayoría de comparaciones de revisiones, estos resultados cambiarán si se crea una nueva revisión.
Este comportamiento en la API es histórico. No es consistente con el modelo conceptual del historial de la página como una serie de revisiones. No hay una revisión previous
para comparar con la primera revisión, ni hay una revisión next
para comparar con la última. Debido a esto, las futuras versiones de MediaWiki pueden dar resultados diferentes para esta llamada a la API.
Uso de la salida HTML
Los prop
valores diff
y parsedcomment
devuelven fragmentos de HTML.
El HTML diff
es una lista de filas de tabla (elementos de <tr>
) que se deben insertar en una tabla con al menos el siguiente marcado:
<table class="diff">
<colgroup>
<col class="diff-marker">
<col class="diff-content">
<col class="diff-marker">
<col class="diff-content">
</colgroup>
<tbody>
DIFF HTML SNIPPET GOES HERE
</tbody>
</table>
Para mostrar metadatos también, p.ej. al usuario o comentario, agrega filas adicionales y coloca los metadatos dentro de un elemento de <td colspan="2">
.
Para asegurarte de que esta diferencia se muestre correctamente (p.ej., que el marcador de diferencia y las columnas de contenido no tengan el mismo ancho), puedes agregar el módulo mediawiki.diff.styles
ResourceLoader a tu página:
<link rel="stylesheet" href="https://www.mediawiki.org/w/load.php?modules=mediawiki.diff.styles&only=styles">
Si deseas mostrar parsedcomment
, igualment querrás agregar el módulo mediawiki.legacy.shared
, que incluye algunos estilos básicos para comentarios y comentarios automáticos:
<link rel="stylesheet" href="https://www.mediawiki.org/w/load.php?modules=mediawiki.legacy.shared&only=styles">
Y si quieres mostrar tanto el HTML diff
como el parsedcomment
en la página, puedes combinar estas dos etiquetas en una:
<link rel="stylesheet" href="https://www.mediawiki.org/w/load.php?modules=mediawiki.legacy.shared|mediawiki.diff.styles&only=styles">