Manual:Pywikibot/PAWS

From mediawiki.org
This page is a translated version of the page Manual:Pywikibot/PAWS and the translation is 69% complete.
詳細は Wikitech:PAWS を参照してください。

この文書では、Pywikibot の簡単な概要をウィキメディア クラウド サービス環境が PAWS (PAWS: A Web Shell) を用いてホストしている notebook を使って説明します。

注意: PAWS ターミナルがコピー & ペーストに対応しているのは、Chromium ベースのブラウザーのみです。 (Google Chrome、Opera、Safari、新しい Microsoft Edge であれば問題なく動作します。) 別のブラウザを使用している場合、コンテキスト メニュー (右クリック) のみでの操作を試すこともできますが、この記事で説明するコマンドを手動で入力する必要があります。 コマンドを書いた bash ファイルを作成して、ターミナル内で bash file.sh を使って呼び出すこともできます。
警告 警告: PAWS のすべてのノートブックとターミナルは、予告なく終了されることがあります。 タスクが数時間以上続く場合は、他の場所 (Toolforge など) での実行が推奨されます。

ウィキメディアのアカウントの作成

このウォークスルーを試すのに必要なのは、ウィキペディア/ウィキメディアのアカウントのみです。作成するには Special:CreateAccount を使用してください。

アカウントを作成したら、https://test.wikipedia.org/にアクセスして、右上にユーザー名が表示されることを確認してください(これはT120327で動作します)

ウィキメディアの新規利用者は、メタ・ウィキ、ウィキペディア、ウィキデータ、コモンズのアカウントでログインしてください。 そして、それぞれで (一番上にある) 保留中のメッセージをすべて読み、削除してください。

notebookにサインイン

ホスティングされた notebook を開始するには、https://hub-paws.wmcloud.org/hub に遷移します。

「Sign in with MediaWiki」をクリックし、「Use OAuth for Authentication」を承認するように求められた際は「Allow」をクリックします。 PAWS にアクセスするのが初めての場合は、サーバーを作成する必要があります。 緑色の"Start my Server"ボタンをクリックしてください。 新しいサーバーを開始する際、通常はしばらく時間がかかります。

これが完了すると、https://paws.wmflabs.org/paws/user/<利用者名>/tree のような URL にリダイレクトされます。

端末の開始

新しい対話型端末を起動するには以下のようにします:

  1. PAWS ホームに移動します。
  2. click: File > New > Terminal

これにより、Linux の「$」プロンプトがある新しいウィンドウが開きます。

この端末はエミュレーターではありません。docker コンテナー上の実物の Linux インストレーションの一部である実物の bash シェルであるため、あらゆる 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>.

user-config.py という名前のファイルを$HOME ディレクトリ (/home/paws) に作成し、mylang および family の変数を追加することで、別のウィキの pywikibot に接続できます:

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:<利用者名> を開きます。

これらのコマンドライン スクリプトそれぞれについて詳細を閲覧するには、「-help」コマンドライン オプションを使用してください。

$ 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

$ ls を実行することで、保存したページを閲覧できるようになるはずです。

スクリプトの実例

ウィキペディアで使用されているウェブサイトへの外部リンクのURLが変更された際、古いリンクが新しいリンクに転送されない場合にはリンク切れが発生する場合があります。 例えばブリタニア百科事典は過去に、http://www.britannica.com/EBchecked/media/からhttp://www.britannica.com/topic/[topic name]/images-videos/*への記事ページのリンクの変更を実施しています。 外部リンク検索検索を行うことで、古いURLが使用されたページの一覧を取得することができます。 これらのリンクを全て手動で更新しようとすると、非常に大きな時間がかかります。 幸いなことにブリタニア百科事典は旧ページから新ページへのリダイレクトを設定しているためすぐに修正を実施する必要はありません。

For a simpler example, English Wikipedia currently contains links to http://britannica.com/EBchecked/ instead of http://www.britannica.com/EBchecked/; i.e. a 'www.' subdomain is missing in the URL.

There are currently 14 cases on English Wikipedia: w:Special:LinkSearch/http://britannica.com/EBchecked/

Wikipedia in other language also have this problem. e.g. there is one case on German Wikipedia: 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.

First, let's list all of the pages which link to 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

Now we check those pages actually have the literal URL in the page; i.e. they are not using a template.

$ 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

Now use replace to add the missing "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

...

In PAWS, and any terminal that supports color, the diff of changes will show the added "www." in green text color, making it easier to find the proposed changes.

Pywikibot の内側

警告 警告: サーバー内のファイルにパスワードを書き込まないでください! ファイルは公開されています!

Next we will use the PAWS Python session.

  1. Go to your PAWS home,
  2. click 'New' on the right hand side, and
  3. select 'Python 3'.

新しいウィンドウが開かれます。

以下の内容をテキストボックスに記述し、上部のメニューから「Run」ボタンを押して下さい(Shiftキー+Enterキーを使って開くこともできます)。

import pywikibot

下部に新たなテキストボックスが表示されます。Run the following to create an APISite object connected to https://test.wikipedia.org/:

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

新しいテキスト ボックスに「site」を入力して「Run」を選択することで内容を表示します。

site

以下のように表示されるはずです

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

page オブジェクトを作成します:

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

複数の行を並列して記述することができるPython3では、上記の内容を以下のように1つのテキストボックスにまとめて書き込むこともできます。

import pywikibot

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

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

The log of your interactive Python session can be saved or downloaded for future reference.

Accessing online documentation in PAWS

Pywikibot documentation may be found at https://doc.wikimedia.org/pywikibot/. It is primarily sourced from docstrings, which can be loaded in the interactive Python 3 notebook using the Python built-in function help().

For example, to look at the arguments for the save method above, run either:

help(page.save)

または

help(pywikibot.Page.save)

Pywikibot スクリプトの編集

The Pywikibot library and scripts are located in /srv/paws, and are read-only. The installed Pywikibot library cannot be modified in PAWS.

Scripts may be modified after copying them into your PAWS home.

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 のセットアップにさらなるヘルプが必要な場合は、IRC チャンネル #pywikibot 接続 または pywikibot@ メーリング リストにお問い合わせください。