Справка:Экспорт

From mediawiki.org
This page is a translated version of the page Help:Export and the translation is 44% complete.
PD Примечание: Редактируя эту страницу, вы соглашаетесь на передачу своего вклада по лицензии CC0.
Подробнее — в проекте Помощь с общественным достоянием.
Некоторые старые изменения для этой страницы были импортированы под лицензией CC BY-SA. Только новые вклады находятся в общественном достоянии (ОД).
PD

Вики-страницы могут быть экспортированы в специальный XML файл для загрузки в другую Вики (если эта функция включена администратором на этой Вики) или использовать его в других целях, например, для анализа содержимого. См. также m:Syndication feeds для экспорта другой информации при просмотре веб-страниц и Help:Import на загруженные страницы.

Как экспортировать страницы

Существует как минимум четыре способа экспорта страниц:

  • Вставьте название статьи в поле в Special:Export или используйте //www.mediawiki.org/wiki/Special:Export/FULLPAGENAME.
  • Резервное копирование с помощью dumpBackup.php сделает дамп всех страниц вики в XML-файл. dumpBackup.php работает только на MediaWiki 1.5 и выше. Вы должны иметь прямой доступ на сервер (например по SSH) для запуска этого скрипта (быть администратором сервера (а не вики)). Дампы проектов Викимедиа регулярно становятся доступны в https://dumps.wikimedia.org/.
  • Примечание: Вам может потребоваться настроить файл AdminSettings.php в для успешного запуска скрипта dumpBackup.php. См. m:MediaWiki для более детальной информации.
  • Существует OAI-PMH - интерфейс для выборки страниц, которые были изменены после определенного времени. Для проектов Викимедиа этот интерфейс не является общедоступным; см. Wikimedia update feed service . OAI-PMH содержит оболочку вокруг формата экспортируемых статей.
  • Используйте Pywikibot framework. Здесь это не объясняется.

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

Дополнительно Вы можете скопировать базу данных SQL. Как делать дампы базы данных в версиях MediaWiki ниже версии 1.5, здесь не будет описано.

Использование 'Special:Export'

Например для: Экспорта всех страниц из пространства имён.

Получить имена страниц для экспорта

Считается, что пример лучше описывает алгоритм.

  1. Перейдите на Special:Allpages и выберете нужные статьи/файлы.
  2. Скопируйте список имен страниц в текстовом редакторе
  3. Необходимо поместить все имена страниц на отдельных строках
    1. Вы можете добиться этого относительно быстро, если вы скопируете части отображаемой страницы с нужными именами, и вставьте в Libre Office Writer/MS Word - используя специальную вставку как неформатированный текст - затем выберете функцию заменить (сочетание клавиш Ctrl+h), введите ^t в "найти", в поле "заменить" введите ^p , а затем нажмите кнопку "Заменить все". (This relies on tabs between the page names; these are typically the result of the fact that the page names are inside td-tags in the html-source.)
    1. The text editor Vim also allows for a quick way to fix line breaks: after pasting the whole list, run the command :1,$s/\t/\r/g to replace all tabs by carriage returns and then :1,$s/^\n//g to remove every line containing only a newline character.
    1. Another approach is to copy the formatted text into any editor exposing the html.

Remove all ‎<tr> and ‎</tr> tags and replace all ‎<td> tags to <tr><td> and ‎<td> tags to </td></tr> the html will then be parsed into the needed format.

Если у вас есть доступ к shell и mysql, то вы можете использовать следующий скрипт:

#
mysql -umike -pmikespassword -hlocalhost wikidbname 
select page_title from wiki_page where page_namespace=0
EOF

Note, replace mike and mikespassword with your own. Also, this example shows tables with the prefix wiki_

  1. Prefix the namespace to the page names (e.g. 'Help:Contents'), unless the selected namespace is the main namespace.
  1. Repeat the steps above for other namespaces (e.g. Category:, Template:, etc.)

Аналогичный скрипт для баз данных PostgreSQL выглядит так:

$ psql -At -U wikiuser -h localhost wikidb -c "select page_title from mediawiki.page"

Note, replace wikiuser with your own, the database will prompt you for a password. This example shows tables without the prefix wiki_ and with the namespace specified as part of the table name.

Alternatively, a quick approach for those with access to a machine with Python installed:

  1. Go to Special:Allpages and choose the desired namespace.
  1. Save the entire webpage as index.php.htm.

Some wikis may have more pages than will fit on one screen of AllPages; you will need to save each of those pages.

  1. Run export_all_helper.py in the same directory as the saved file.

You may wish to pipe the output to a file; e.g. python export_all_helper.py > main to send it to a file named "main".

  1. Save the page names output by the script.

Выполнить экспорт

  • Go to Special:Export and paste all your page names into the textbox, making sure there are no empty lines.
  • Click 'Submit query'
  • Save the resulting XML to a file using your browser's save facility.

и наконец...

  • Открыть файл XML в текстовом редакторе. Прокрутите вниз, чтобы проверить сообщения об ошибках.

Теперь вы можете использовать этот XML-файл для выполнения импорта.

Экспорт полной истории

Exporting the revision history may be desirable to retain authorship information and attribution. A checkbox in the Special:Export interface selects whether to export the full history (all versions of an article) or the most recent version of articles. A maximum of 100 revisions are returned; other revisions can be requested as detailed in Parameters to Special:Export .


Формат экспорта

The format of the XML file you receive is the same in all ways. It is codified in XML Schema at https://www.mediawiki.org/xml/export-0.10.xsd This format is not intended for viewing in a web browser. Some browsers show you pretty-printed XML with "+" and "-" links to view or hide selected parts. Alternatively the XML-source can be viewed using the "view source" feature of the browser, or after saving the XML file locally, with a program of choice. If you directly read the XML source it won't be difficult to find the actual wikitext. If you don't use a special XML editor "<" and ">" appear as &lt; and &gt;, to avoid a conflict with XML tags; to avoid ambiguity, "&" is coded as "&amp;".

In the current version the export format does not contain an XML replacement of wiki markup (see Wikipedia DTD for an older proposal). You only get the wikitext as you get when editing the article.

Пример

  <mediawiki xml:lang="en">
    <page>
      <title>Page title</title>
      <restrictions>edit=sysop:move=sysop</restrictions>
      <revision>
        <timestamp>2001-01-15T13:15:00Z</timestamp>
        <contributor><username>Foobar</username></contributor>
        <comment>I have just one thing to say!</comment>
        <text>A bunch of [[Special:MyLanguage/text|text]] here.</text>
        <minor />
      </revision>
      <revision>
        <timestamp>2001-01-15T13:10:27Z</timestamp>
        <contributor><ip>10.0.0.2</ip></contributor>
        <comment>new!</comment>
        <text>An earlier [[Special:MyLanguage/revision|revision]].</text>
      </revision>
    </page>
    
    <page>
      <title>Talk:Page title</title>
      <revision>
        <timestamp>2001-01-15T14:03:00Z</timestamp>
        <contributor><ip>10.0.0.2</ip></contributor>
        <comment>hey</comment>
        <text>WHYD YOU LOCK PAGE??!!! i was editing that jerk</text>
      </revision>
    </page>
  </mediawiki>

DTD

Вот неофициальное, короткое описание версии формата Document Type Definition. Если вы не знаете, что такое DTD, просто игнорируйте это.

<!ELEMENT mediawiki (siteinfo,page*)>
<!-- version contains the version number of the format (currently 0.3) -->
<!ATTLIST mediawiki
  version  CDATA  #REQUIRED 
  xmlns CDATA #FIXED "https://www.mediawiki.org/xml/export-0.3/"
  xmlns:xsi CDATA #FIXED "http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation CDATA #FIXED
    "https://www.mediawiki.org/xml/export-0.3/ https://www.mediawiki.org/xml/export-0.3.xsd"
  xml:lang  CDATA #IMPLIED
>
<!ELEMENT siteinfo (sitename,base,generator,case,namespaces)>
<!ELEMENT sitename (#PCDATA)>      <!-- name of the wiki -->
<!ELEMENT base (#PCDATA)>          <!-- url of the main page -->
<!ELEMENT generator (#PCDATA)>     <!-- MediaWiki version string -->
<!ELEMENT case (#PCDATA)>          <!-- how cases in page names are handled -->
   <!-- possible values: 'first-letter' | 'case-sensitive'
        'case-insensitive' option is reserved for future -->
<!ELEMENT namespaces (namespace+)> <!-- list of namespaces and prefixes -->
  <!ELEMENT namespace (#PCDATA)>     <!-- contains namespace prefix -->
  <!ATTLIST namespace key CDATA #REQUIRED> <!-- internal namespace number -->
<!ELEMENT page (title,id?,restrictions?,(revision|upload)*)>
  <!ELEMENT title (#PCDATA)>         <!-- Title with namespace prefix -->
  <!ELEMENT id (#PCDATA)> 
  <!ELEMENT restrictions (#PCDATA)>  <!-- optional page restrictions -->
<!ELEMENT revision (id?,timestamp,contributor,minor?,comment?,text)>
  <!ELEMENT timestamp (#PCDATA)>     <!-- according to ISO8601 -->
  <!ELEMENT minor EMPTY>             <!-- minor flag -->
  <!ELEMENT comment (#PCDATA)> 
  <!ELEMENT text (#PCDATA)>          <!-- Wikisyntax -->
  <!ATTLIST text xml:space CDATA  #FIXED "preserve">
<!ELEMENT contributor ((username,id) | ip)>
  <!ELEMENT username (#PCDATA)>
  <!ELEMENT ip (#PCDATA)>
<!ELEMENT upload (timestamp,contributor,comment?,filename,src,size)>
  <!ELEMENT filename (#PCDATA)>
  <!ELEMENT src (#PCDATA)>
  <!ELEMENT size (#PCDATA)>

Обработка экспорта XML

Many tools can process the exported XML. If you process a large number of pages (for instance a whole dump) you probably won't be able to get the document in main memory so you will need a parser based on SAX or other event-driven methods.

You can also use regular expressions to directly process parts of the XML code. This may be faster than other methods but not recommended because it's difficult to maintain.

Please list methods and tools for processing XML export here:


Детали и советы

  • Для того, чтобы определить пространство имён для страницы, нужно сравнить название страницы с префиксами, обозначенными на странице /mediawiki/siteinfo/namespaces/namespace
  • Возможные ограничения
    • sysop - защищенные страницы

Зачем экспортировать

Почему просто не скачать базу данных?

Suppose you are building a piece of software that at certain points displays information that came from Wikipedia. If you want your program to display the information in a different way than can be seen in the live version, you'll probably need the wikicode that is used to enter it, instead of the finished html.

Also if you want to get all of the data, you'll probably want to transfer it in the most efficient way that's possible. The Wikimedia servers need to do quite a bit of work to convert the wikicode into html. That's time consuming both for you and for the Wikimedia servers, so simply spidering all pages is not the way to go.

To access any article in XML, one at a time, link to:

Special:Export/Title_of_the_article

См. также