API:Alllinks/ru

This page is a translated version of the page API:Alllinks and the translation is 96% complete.
Версия MediaWiki:
1.11

GET-запрос на перечисление всех ссылок, указывающих на заданное пространство имён , упорядоченых по названию.

Этот модуль можно использовать как генератор.

Документация по API


(main | query | alllinks)
  • This module requires read rights.
  • This module can be used as a generator.
  • Source: MediaWiki
  • License: GPL-2.0-or-later

Enumerate all links that point to a given namespace.

Specific parameters:
Other general parameters are available.
alcontinue

When more results are available, use this to continue. More detailed information on how to continue queries can be found on mediawiki.org.

alfrom

The title of the link to start enumerating from.

alto

The title of the link to stop enumerating at.

alprefix

Search for all linked titles that begin with this value.

alunique

Only show distinct linked titles. Cannot be used with alprop=ids.

When used as a generator, yields target pages instead of source pages.

Type: boolean (details)
alprop

Which pieces of information to include:

ids
Adds the page ID of the linking page (cannot be used with alunique).
title
Adds the title of the link.
Values (separate with | or alternative): ids, title
Default: title
alnamespace

The namespace to enumerate.

One of the following values: -1, -2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 90, 91, 92, 93, 100, 101, 102, 103, 104, 105, 106, 107, 486, 487, 710, 711, 828, 829, 1198, 1199, 2600, 5500, 5501
Default: 0
allimit

How many total items to return.

Type: integer or max
The value must be between 1 and 500.
Default: 10
aldir

The direction in which to list.

One of the following values: ascending, descending
Default: ascending
Examples:
List linked titles, including missing ones, with page IDs they are from, starting at B.
api.php?action=query&list=alllinks&alfrom=B&alprop=ids|title [open in sandbox]
List unique linked titles.
api.php?action=query&list=alllinks&alunique=&alfrom=B [open in sandbox]
Gets all linked titles, marking the missing ones.
api.php?action=query&generator=alllinks&galunique=&galfrom=B [open in sandbox]
Gets pages containing the links.
api.php?action=query&generator=alllinks&galfrom=B [open in sandbox]

Пример

По умолчанию этот модуль возвращает дубликаты, если страница содержит несколько ссылок, указывающих на одно и то же пространство имен. В этом примере alunique=1 используется для удаления повторяющихся заголовков в ответе.

GET-запрос

Перечислить различные ссылки (т.е. без дубликатов), которые указывают на основное пространство имен.


Ответ

{
    "batchcomplete": "",
    "continue": {
        "alcontinue": "!!!!Hashtagging",
        "continue": "-||"
    },
    "query": {
        "alllinks": [
            {
                "ns": 0,
                "title": "!"
            },
            {
                "ns": 0,
                "title": "!!"
            },
            {
                "ns": 0,
                "title": "!!!"
            },
            ...
}

Пример кода

Python

#!/usr/bin/python3

"""
    get_alllinks.py

    MediaWiki API Demos
    Demo of `Alllinks` module: List links pointing to the given namespace.

    MIT License
"""

import requests

S = requests.Session()

URL = "https://en.wikipedia.org/w/api.php"

PARAMS = {
    "action": "query",
    "format": "json",
    "list": "alllinks",
    "alnamespace": "0",
    "alunique": "1"
}

R = S.get(url=URL, params=PARAMS)
DATA = R.json()

LINKS = DATA["query"]["alllinks"]

for l in LINKS:
    print(l["title"])

PHP

<?php
/*
    get_alllinks.php

    MediaWiki API Demos
    Demo of `Alllinks` module: List links pointing to the given namespace.

    MIT License
*/

$endPoint = "https://en.wikipedia.org/w/api.php";
$params = [
    "action" => "query",
    "format" => "json",
    "list" => "alllinks",
    "alnamespace" => "0",
    "alunique" => "1"
];

$url = $endPoint . "?" . http_build_query( $params );

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$output = curl_exec( $ch );
curl_close( $ch );

$result = json_decode( $output, true );

foreach( $result["query"]["alllinks"] as $k => $v ) {
    echo( $v["title"] . "\n" );
}

JavaScript

/*
    get_alllinks.js

    MediaWiki API Demos
    Demo of `Alllinks` module: List links pointing to the given namespace.

    MIT License
*/

var url = "https://en.wikipedia.org/w/api.php"; 

var params = {
    action: "query",
    format: "json",
    list: "alllinks",
    alnamespace: "0",
    alunique: "1"
};

url = url + "?origin=*";
Object.keys(params).forEach(function(key){url += "&" + key + "=" + params[key];});

fetch(url)
    .then(function(response){return response.json();})
    .then(function(response) {
        var links = response.query.alllinks;
        for (var l in links) {
            console.log(links[l].title);
        }
    })
    .catch(function(error){console.log(error);});

MediaWiki JS

/*
	get_alllinks.js

	MediaWiki API Demos
	Demo of `Alllinks` module: List links pointing to the given namespace.

	MIT License
*/

var params = {
		action: 'query',
		format: 'json',
		list: 'alllinks',
		alnamespace: '0',
		alunique: '1'
	},
	api = new mw.Api();

api.get( params ).done( function ( data ) {
	var links = data.query.alllinks,
		l;
	for ( l in links ) {
		console.log( links[ l ].title );
	}
} );

Возможные ошибки

Код Информация
badcontinue Некорректный параметр continue. Вы должны передать значение, возвращённое предыдущим запросом.
invalidparammix Параметр alprop=ids не может быть использован одновременно с alunique.
Это происходит, когда вы используете alprop=ids и alunique вместе

Дополнительная информация

  • Как и другие модули ссылок в API действий , этот модуль возвращает заголовки страниц, которые ссылаются на пространство имен, а не точные URI для этих страниц.
  • Этот модуль можно использовать как генератор.
  • Предыдущие версии возвращали ошибку, если пользователь пытался запустить этот модуль в качестве генератора, и alunique был установлен в true. Это было изменено в v1.24, чтобы позволить использовать модуль в качестве генератора, даже если alunique истинно.

См. также

  • API:Backlinks - список ссылок на данную страницу.
  • API:Linkshere - аналогично API:Backlinks , получает ссылки на данную страницу. Обратите внимание, что в отличие от API:Backlinks , который является модулем list , API:Linkshere является модулем prop . См. соответствующие страницы API:Свойства и API:Списки , чтобы узнать, как отличаются эти два вида модулей.
  • API: Ссылки - извлекает ссылки на заданной странице или страницах.