Manuel:Pywikibot/PAWS

From mediawiki.org
This page is a translated version of the page Manual:Pywikibot/PAWS and the translation is 80% complete.
Voir Wikitech:PAWS pour plus d'informations.

Ce document donne une vision rapide et interactive de Pywikibot en utilisant un notebook hébergé sur le Services cloud Wikimedia Cloud via PAWS (PAWS: A Web Shell).

Le Terminal PAWS supporte le copier-coller uniquement dans les navigateurs basés sur Chromium. (Google Chrome, Opera et Safari opérationels). Si vous utilisez un autre navigateur, vous pouvez utiliser le menu contextuel (clic droit) ou taper manuellement les commandes présentes dans ce guide. Vous pouvez aussi créer un fichier Bash dont le contenu contiendrait la commande, exécutable avec bash file.sh
Avertissement Avertissement : Tous les ordinateurs portables et terminaux de PAWS peuvent être résiliés sans préavis. Vous êtes encouragé à exécuter votre tâche sur d'autres emplacements (tels que Toolforge) si votre tâche dure plus que plusieurs heures.

Créer un compte Wikimédia

Pour suivre ce guide, vous avez seulement besoin d'un compte Wikipédia/Wikimédia. Utilisez Special:CreateAccount pour en créer un.

Une fois votre compte créé, merci de vérifier,en allant sur https://test.wikipedia.org/ que votre identifiant apparaît en haut à droite. (fonctionne depuis tâche T120327).

Si vous êtes un nouvel utilisateur sur Wikimedia, connectez-vous avec votre compte sur meta.Wikimedia, Wikipedia, Wikidata et Commons. Et dans chacun d'eux, lisez et supprimez tous les messages en attente que vous avez (en haut).

Se connecter au Notebook

Pour démarrer un Notebook en ligne, aller sur https://hub-paws.wmcloud.org/hub

Cliquer sur Sign in with MediaWiki, puis sur Autoriser lors de l'OAuth Authentication. Lors du premier accès à PAWS, vous devez créer votre serveur. Cliquez sur le bouton vert Start my Server. Il est normal d'attendre quelques minutes lors du démarrage.

Une fois celui-ci terminé, vous serez redirigé à une page de type https://paws.wmflabs.org/paws/user/<nom d'utilisateur>/tree

Démarrer un terminal

Pour démarrer une nouvelle terminal interactive numérique,

  1. Accédez à votre PAWS home
  2. cliq: File > Nouvelle > Terminal

Cela vais ouvrir une nouvelle fenêtre avec une invite de Linux '$'.

Le terminal est réel, c'est un bash shell, dans une installation appartenant à un docker container. Vous pouvez donc utilisez n'importe quelle commande bash reconnue par Linux.

Pour lister les fichiers, utilisez 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.


Se connecter au wiki

Ceci établira votre compte sur le serveur et vous permettra de vous logguer depuis la ligne de commande. Cette commande permet de vérifier que vous pouvez vous connecter au wiki de test. Celui-ci utilise OAuth, il n'est donc pas nécessaire de saisir son mot de passe.

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

Vous pouvez connecter pywikibot à un wiki différent en créant un fichier nomé user-config.py dans votre dossier $HOME et en ajoutant les variables mylang et 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.


Créer une page

La commande suivante permet de créer une page de test. Remplacez '<username>' par votre nom d'utilisateur, puis validez la modification de la page en appuyant sur Y (oui) lorsque cela vous est demandé.

$ 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

Vous avez modifié le Wiki ! Vous pouvez contempler en ouvrant $u dans votre navigateur.

Vous pouvez en savoir plus sur chacun de ces scripts avec le paramètre '-help' .

$ pwb.py add_text -help
...

Lire une page

La recherche de plusieurs pages est possible via la commande listpages.

Pour obtenir le contenu de la page créée précédemment, entrez la commande suivante :

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

Maintenant, s'il te fais l'exécution du $ ls, la page enregistrée devrait être en vue.

Un exemple de script réel

Losqu'un site utilisé par Wikipédia change son URL, les liens dans Wikipédia deviennent caducs, et probablement des liens morts si le site web ne redirige pas des anciennes URLs vers les nouvelles. L'encyclopédie Britanica (EP) a changé ses liens , déplaçant les pages de http://www.britannica.com/EBchecked/media/ à http://www.britannica.com/topic/[topic name]/images-videos/*. Vous pouvez trouver la liste des des anciennes URLS sur la Wikipédia anglaise à w:Special:LinkSearch/http://www.britannica.com/EBchecked/media. Mettre à jours à la main tous ces liens serait chronophage. Heureusement, EB a maintenu des redirections des anciennes URLS vers les nouvelles. Ainsi, il n'est pas nécessaire de régler le problème immédiatement.

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.

Utilisation plus complète

Avertissement Avertissement : Ne pas écrire les mots de passe dans les fichiers du serveur, ils sont publics.

Nous allons à nouveau utiliser les Notebook fournis par PAWS et ses commandes Python.

  1. Aller sur la page d'accueil
  2. Cliquer sur New en haut à droite, puis
  3. Sélectionner Python 3

Une nouvelle fenêtre s'ouvre.

Dans la zone de saisie, entrez la commande suivante. Pour l’exécuter, cliquez sur Run dans le menu Cell (ou le raccourci clavier Shift + Enter).

import pywikibot

Une nouvelle zone de saisie apparaît dessous. La commande suivante permet de créer un objet nommé APISite et de se connecter au wiki de test.

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

Appelez l'objet précédemment créé puis cliquez sur Run.

site

Vous obtenez :

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

Créer un objet de type page :

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

Vérifier qu'il est existant en l’appelant :

page.exists()

Vous obtenez :

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

Afficher le contenu de la page :

page.text

Le remplacer par un nouveau contenu :

page.text = 'Hello world'

Et enfin sauvegarder la page :

page.save()

Vous obtenez :

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

La Notebook interactif du langage Python 3 autorise l’exécution simultanée de plusieurs lignes? Par exemple vous pouvez ajouter les lignes ci dessous dans une seule cellule puis cliquez sur Run :

import pywikibot

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

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

Il est possible de télécharger les logs (résultats) pour une référence future.

Documentation en ligne

La documentation de Pywikibot peut être obtenue à l'adresse https://doc.wikimedia.org/pywikibot/. Elle provient principalement de docstrings, qui peut également être consultée directement depuis le terminal interactif Python 3 avec la fonction help().

Par exemple, pour obtenir la documentation de la commande utilisée précédemment :

help(page.save)

ou

help(pywikibot.Page.save)

Éditer les scripts Pywikibot

La bibliothèque Pywikibot est enregistrée dans le dossier /srv/paws, accessible en lecture seule.

Il est néanmoins possible de les modifier en les copiant dans votre espace personnel.

Par exemple, pour exécuter une version modifiée de "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.)

Voir aussi


Si vous avez besoin de plus d'aide pour configurer votre Pywikibot, consultez le canal IRC #pywikibot connecter ou la liste de diffusion pywikibot@.