Посібник:Pywikibot/PAWS

From mediawiki.org
This page is a translated version of the page Manual:Pywikibot/PAWS and the translation is 71% complete.
Outdated translations are marked like this.
Див. Wikitech:PAWS для докладнішої інформації.

Цей документ надає швидкий інтерактивний огляд Pywikibot із використанням notebook, який розташований у середовищі лабораторій Вікімедіа та використовує PAWS (PAWS: A Web Shell).

Зауважте, що PAWS Terminal підтримує копіювання та вставку лише у браузери на основі Chromium (Google Chrome, Opera, Safari та новий Microsoft Edge підходять.) Якщо Ви використовуєте інший браузер, ви можете спробувати лише контекстне меню (клацніть правою кнопкою миші) або вам треба вручну вводити команди, згадані в цьому проходженні. Ви також можете створити bash-файл зі вмістом команди та викликати в терміналі з bash file.sh.
Увага Увага: All notebooks and terminals in PAWS are subject to termination without notice. You are encouraged to run your task on other places (such as Toolforge) if your task lasts for more than hours.

Створення облікового запису Вікімедіа

Для дотримання цього проходження Вам потрібний лише обліковий запис Вікіпедії чи Вікімедіа. Використовуйте Special:CreateAccount для створення такого.

Щойно Ви створили обліковий запис, будь ласка, відвідайте https://test.wikipedia.org/ та перевірте, що Ваше ім'я користувача з'явилося у верхньому правому кутку (це працює навколо завдання T120327).

If you are a new user on Wikimedia log in with your account on Meta-Wiki, Wikipedia, Wikidata, and Commons. And in each of them read and delete all pending messages you have (on the top).

Вхід до записника

Для запуску розміщеного записника ідіть до https://hub-paws.wmcloud.org/hub

Натисніть «Увійти за допомогою MediaWiki», а потім «Дозволяю», коли попросять схвалити «Використовувати OAuth для автентифікації». Під час першого доступу до PAWS Вам необхідно створити сервер. Натисніть зелену кнопку «Запустити мій Сервер». Нормально почекати кілька хвилин, поки новий сервер запуститься.

Щойно це завершиться, Вас буде переспрямовано до URL на кшталт https://hub-paws.wmcloud.org/user/<username>/lab

Запуск терміналу

Для запуску нового інтерактивного терміналу,

  1. Ідіть до свого дому PAWS
  2. натисніть «Новий» праворуч, і
  3. виберіть «Термінал».
  1. click: File > New > Terminal

Це відкриє нове вікно з URL $paws та запитом Linux «$».

Цей термінал не є емулятором. Це справжня оболонка bash як частина справжньої інсталяції Linux, яка сидить на докерному контейнері, то ж Ви можете використовувати будь-яку команду bash і використовувати будь-які команди, доступні на Linux, які було встановлено.

Щоб побачити деякі доступні команди, використовуйте ls /bin/.

$ ls /bin/
bash         cat            domainname  journalctl  mkdir          pwd         stty                            tar           zcmp
unzip2       chacl          echo        kill        mknod          rbash       su                              tempfile      zdiff
../..
$ ls /usr/bin/
2to3-3.4                 dvipdf                     lcf                         printf               systemd-path                         
X11                      dwp                        ld                          prlimit              systemd-run
../..

To see them all, press TAB twice.


Вхід до Вікіпедії

Це встановить Ваш обліковий запис на сервері та дозволить Вам входити з командного рядка. Наступна команда повинна підтвердити, що Ви входите до тестової Вікіпедії. Вона використовує OAuth, то ж немає необхідності вводити пароль.

$ pwb.py login
Logging in to wikipedia:test as <username>
Logged in on wikipedia:test as <username>.

Ви можете під'єднати pywikibot до різних Вікіпедій шляхом створення файлу під назвою user-config.py у своїй $HOME папці (/home/paws) та додавання змінних mylang і family:

mylang = 'test'
family = 'wikipedia'

You can type vim user-config.py in the terminal, then I to insert text, add the text, then Esc to exist insert mode, then :wq and Enter to finishing editing.


Створення сторінки

Для створення сторінки введіть наступну команду в терміналі, замінивши «<username>» своїм іменем користувача та натиснувши «Y» при запиті на підтвердження Ваших змін:

$ pwb.py add_text -up -talk -page:"User talk:<username>" -text:"Hello. ~~~~"
Loading User talk:<username>...

>>> User talk:<username> <<<
@@ -0,0 +1 @@
+ Hello. ~~~~

Do you want to accept these changes? ([Y]es, [N]o, [a]ll, open in [b]rowser): Y
Page [[User talk:<username>]] saved

Ви відредагували Вікіпедію. Перегляньте свої зміни відкриттям https://test.wikipedia.org/wiki/User_talk:<username> у своєму веб-браузері.

Ви можете прочитати більше про кожен із цих сценаріїв командного рядка за допомогою опції «h» командного рядка.

$ pwb.py add_text -help
...

Завантаження сторінки

Завантаження багатьох сторінок досягається командою «listpages».

Для отримання вмісту створеної Вами сторінки в попередньому розділі введіть наступну команду:

$ pwb.py listpages -page:"User talk:<username>" -save
   1 <username>
Saving User talk:<username> to /home/paws/User_talk_<username>
1 page(s) found

Тепер, якщо Ви підете до свого [$url списку файлів PAWS], збережена сторінка повинна існувати.

Приклад реального скрипту

When a website used on Wikipedia changes its URL, the links on Wikipedia become outdated, and possible also dead links if the website doesn't redirect from the old URLs to the new URLs. For example, Encyclopedia Britannica (EB) has changed their links, such as moving pages from http://www.britannica.com/EBchecked/media/ to http://www.britannica.com/topic/[topic name]/images-videos/*. You can find the list of usages of the old URL on English Wikipedia at w:Special:LinkSearch/http://www.britannica.com/EBchecked/media. Updating all those links manually will be very time consuming. Thankfully EB has maintained redirects from their old URLs to the new URLs, so this does not need to be fixed immediately.

Для простішого прикладу Англійська Вікіпедія наразі містить посилання до http://britannica.com/EBchecked/ замість http://www.britannica.com/EBchecked/; тобто піддомен «www.» відсутній у цьому URL.

Наразі існує 14 cases в Англійській Вікіпедії: w:Special:LinkSearch/http://britannica.com/EBchecked/

Вікіпедія іншою мовою також має цю проблему. Наприклад, один case в Німецькій Вікіпедії: w:de:Spezial:Weblinksuche/http://britannica.com/EBchecked/

In order to fix those links, we can use Pywikibot replace.py script. In this demo we will use the '-simulate' argument to avoid writing to the wiki, as there are strict rules about automated editing of English Wikipedia.

Спочатку давайте перелічимо всі сторінки, що посилаються на http://britannica.com/EBchecked/.

$ pwb.py listpages -lang:en -weblink:"britannica.com/EBchecked/"
   1 Bhatner fort
   2 Mohammad Ishaq Khan
   3 Fringe theories/Noticeboard/Archive 7
   4 El Riego phase
   5 Catalonia/Archive 4
   6 Stephen I of Hungary
   7 Stephen I of Hungary/Archive 1
   8 Väinö Tanner
   9 Tokaji
  10 Transylvania/Archive5
  11 Hungarians in Romania
  12 Transylvania
  13 Uttarakhand
  14 Françoise Giroud
14 page(s) found

Тепер ми перевіримо ті сторінки, що дійсно мають літерал URL на сторінці, тобто вони не використовують шаблон.

$ pwb.py listpages -lang:en -weblink:"britannica.com/EBchecked/" -grep:"britannica.com\/EBchecked"
   1 Bhatner fort
   2 Mohammad Ishaq Khan
   3 Fringe theories/Noticeboard/Archive 7
   4 El Riego phase
   5 Catalonia/Archive 4
   6 Stephen I of Hungary
   7 Stephen I of Hungary/Archive 1
   8 Väinö Tanner
   9 Tokaji
  10 Transylvania/Archive5
  11 Hungarians in Romania
  12 Transylvania
  13 Uttarakhand
  14 Françoise Giroud
14 page(s) found

Тепер використаємо заміну для додавання пропущеного «www.»

$ pwb.py replace -lang:en -simulate -weblink:"britannica.com/EBchecked/" -grep:"britannica.com\/EBchecked" "http://britannica.com/EBchecked/" "http://www.britannica.com/EBchecked/"
The summary message for the command line replacements will be something like: Bot: Automated text replacement  (-http://britannica.com/EBchecked/ +http://www.britannica.com/EBchecked/)
Press Enter to use this automatic message, or enter a description of the
changes your bot will make: 
Logging in to wikipedia:en as <username>
Retrieving 14 pages from wikipedia:en.
Retrieving 14 pages from wikipedia:en.


>>> Stephen I of Hungary <<<
@@ -47 +47 @@
- Stephen's birth date is uncertain because it was not recorded in contemporaneous documents.{{sfn|Györffy|1994|p=64}} Hungarian and Polish chronicles written centuries later give three different years: 967, 969 and 975.{{sfn|Kristó|2001|p=15}} The unanimous testimony of his three late 11th-century or early 12th-century [[hagiographies]] and other Hungarian sources, which state that Stephen was "still an adolescent" in 997,<ref>''Hartvic, Life of King Stephen of Hungary'' (ch. 5), p. 381.</ref> substantiate the reliability of the later year (975).{{sfn|Györffy|1994|p=64}}{{sfn|Kristó|2001|p=15}} Stephen's ''[[Life of Saint Stephen, King of Hungary (Vita minor)|Lesser Legend]]'' adds that he was born in [[Esztergom]],{{sfn|Györffy|1994|p=64}}{{sfn|Kristó|2001|p=15}}<ref name=Britannica>{{cite encyclopedia|title=Stephen I|url=http://britannica.com/EBchecked/topic/565415/Stephen-I|encyclopedia=[[Encyclopædia Britannica]]|publisher=Encyclopædia Britannica, Inc.|year=2008|accessdate=2008-07-29}}</ref> which implies that he was born after 972 because his father, [[Géza, Grand Prince of the Hungarians]], chose Esztergom as royal residence around that year.{{sfn|Györffy|1994|p=64}} Géza promoted the spread of Christianity among his subjects by force, but never ceased worshipping pagan gods.{{sfn|Kontler|1999|p=51}}{{sfn|Berend|Laszlovszky|Szakács|2007|p=331}} Both his son's ''[[Life of Saint Stephen, King of Hungary (Vita maior)|Greater Legend]]'' and the nearly contemporaneous [[Thietmar of Merseburg]] described Géza as a cruel monarch, suggesting that he was a despot who mercilessly consolidated his authority over the rebellious Hungarian lords.{{sfn|Berend|Laszlovszky|Szakács|2007|p=331}}{{sfn|Bakay|1999|p=547}}
+ Stephen's birth date is uncertain because it was not recorded in contemporaneous documents.{{sfn|Györffy|1994|p=64}} Hungarian and Polish chronicles written centuries later give three different years: 967, 969 and 975.{{sfn|Kristó|2001|p=15}} The unanimous testimony of his three late 11th-century or early 12th-century [[hagiographies]] and other Hungarian sources, which state that Stephen was "still an adolescent" in 997,<ref>''Hartvic, Life of King Stephen of Hungary'' (ch. 5), p. 381.</ref> substantiate the reliability of the later year (975).{{sfn|Györffy|1994|p=64}}{{sfn|Kristó|2001|p=15}} Stephen's ''[[Life of Saint Stephen, King of Hungary (Vita minor)|Lesser Legend]]'' adds that he was born in [[Esztergom]],{{sfn|Györffy|1994|p=64}}{{sfn|Kristó|2001|p=15}}<ref name=Britannica>{{cite encyclopedia|title=Stephen I|url=http://www.britannica.com/EBchecked/topic/565415/Stephen-I|encyclopedia=[[Encyclopædia Britannica]]|publisher=Encyclopædia Britannica, Inc.|year=2008|accessdate=2008-07-29}}</ref> which implies that he was born after 972 because his father, [[Géza, Grand Prince of the Hungarians]], chose Esztergom as royal residence around that year.{{sfn|Györffy|1994|p=64}} Géza promoted the spread of Christianity among his subjects by force, but never ceased worshipping pagan gods.{{sfn|Kontler|1999|p=51}}{{sfn|Berend|Laszlovszky|Szakács|2007|p=331}} Both his son's ''[[Life of Saint Stephen, King of Hungary (Vita maior)|Greater Legend]]'' and the nearly contemporaneous [[Thietmar of Merseburg]] described Géza as a cruel monarch, suggesting that he was a despot who mercilessly consolidated his authority over the rebellious Hungarian lords.{{sfn|Berend|Laszlovszky|Szakács|2007|p=331}}{{sfn|Bakay|1999|p=547}}

Do you want to accept these changes? ([y]es, [N]o, [e]dit, open in [b]rowser, [a]ll, [q]uit): N

...

У PAWS і будь-якому терміналі з підтримкою кольору різниця змін показуватиме додавання «www.» зеленим кольором тексту, спрощуючи пошук пропонованих змін.

Всередині Pywikibot

Увага Увага: Не пишіть паролі у файлах серверу, файли публічні!

Далі ми використовуватимемо сеанс PAWS Python.

  1. Ідіть до свого дому PAWS,
  2. натисніть «Новий» праворуч, і
  3. виберіть «Python 3».

Це відкриє нове вікно.

У текстовому полі введіть наступне та в меню Комірка виберіть «Запуск» (або натисніть Shift+Enter для запуску).

import pywikibot

Нове текстове вікно з'явиться нижче. Запустіть наступне для створення об'єкту APISite, підключеного до https://test.wikipedia.org/:

site = pywikibot.Site('test', 'wikipedia')

Опишіть «сайт» введенням його в нове текстове вікно та виберіть «Запуск».

site

Повинно показатися

 Out[3]: APISite("test", "wikipedia")

Створено об'єкт сторінки:

page = pywikibot.Page(site, 'test')

Перевірте його існування запуском:

page.exists()

Повинно вивестись

 VERBOSE:pywiki:Found 1 wikipedia:test processes running, including this one.
 Out[5]: True

Показався текст на сторінці:

page.text

Зміна тексту сторінки в об'єкті:

page.text = 'Hello world'

Збереження сторінки на Вікіпедію:

page.save()

Відгук повинен бути:

Page [[Test]] saved
INFO:pywiki:Page [[Test]] saved

Інтерактивний записник Python 3 дозволяє запускати багато рядків разом. Вони повинні бути в одному текстовому полі та Запущені

import pywikibot

site = pywikibot.Site('test', 'wikipedia')
page = pywikibot.Page(site, 'test')

page.text = 'Hello world!'
page.save()

Журнал Вашого інтерактивного сеансу Python може бут збережений або завантажений для майбутніх посилань.

Доступ до онлайн-документації у PAWS

Документація Pywikibot може бути знайдена на https://doc.wikimedia.org/pywikibot/. Вона процитована переважно з docstrings, який можна завантажити в інтерактивний записник Python 3, використовуючи вбудовану функцію Python help().

Наприклад, подивимось аргументи вищезгаданого методу збереження, запустивши:

help(page.save)

або

help(pywikibot.Page.save)

Редагування скриптів Pywikibot

Бібліотека та сценарії Pywikibot розташовані в /srv/paws і доступні лише для читання. Встановлена бібліотека Pywikibot не може змінюватися у PAWS.

Скрипти можуть змінюватися після їх копіювання до свого дому PAWS.

For example, to run a modified "checkimages.py":

  1. In the terminal, enter cp /srv/paws/pwb/scripts/checkimages.py ~
  1. In a browser, go to your PAWS home and click on the file checkimages.py.
  1. In the browser, you can edit the file.

Edit the code -- for instance, just after the start = time.time() code on line 1775, add a new line 1776 that will print out your name: print("MYNAME's version.")

  1. In the editing interface, use the File menu and click Save to save your modifications.
  1. In the terminal, enter pwb.py ~/checkimages.py -simulate -limit:10

(If no '-limit:x' defined, the program would run until all images checked, it may take long time.)

Див. також


Якщо вам потрібна додаткова допомога щодо налаштування вашого Pywikibot, відвідайте #pywikibot IRC-канал connect або pywikibot@ список розсилки.