« Programmation Python/Programmer en deux minutes/l'interface de Wikipédia pour programmer » : différence entre les versions

Contenu supprimé Contenu ajouté
Aucun résumé des modifications
Aucun résumé des modifications
Ligne 1 :
Utiliser un [[w:Services Web|service Web]] via son interface de programmation consiste à utiliser les ressources fournies sur demande par divers sites Internet.
<noinclude>{{Python}}</noinclude>
 
Par exemple vous pouvez demander aux serveurs de Wikibooks [//fr.wikibooks.org/w/api.php?action=query&prop=info|revisions&titles=Accueil des informations] concernant tel ou tels sujets dans tel format de données.
Nous allons écrire un script en Python et l'exécuter dans une console. Le script va utiliser deux ensembles de commandes définis dans la bibliothèque fournie à l'installation du langage.
 
Autre exemple vous pouvez demander aux serveurs de Google tel ou tel [http://chart.apis.google.com/chart?cht=lc&chd=t:26,35,15,28,25,18,27,28,21,29,22,29,19,21,8,23,20,27,17&chds=0,50&chs=500x400&chl=janvier|mars|mai graphique].
[[mw:API/fr|L'interface avec Wikipédia]] se fait via des requêtes à :
 
{{ébauche}}
https://fr.wikipedia.org/w/api.php?
==Exemple==
===Wikipedia===
 
L'[[interface de programmation]] du service web Wikipédia francophone est disponible [//fr.wikipedia.org/w/api.php ici]
Par exemple :
 
{{ApiEx
https://fr.wikipedia.org/w/api.php?action=query&prop=info|revisions&titles=Accueil
|desc=Obtenir les informations à propos de la dernière révision de la page [[Accueil]] :
|p1=action=query
|p2=prop=info{{!}}revisions
|p3=rvprop=timestamp
|p4=titles=Accueil
|result=<source lang="xml"><?xml version="1.0"?>
<?xml version="1.0"?>
<api>
<query>
<pages>
<page pageid="15169" ns="0" title="Accueil" touched="2009-05-10T14:43:08Z" lastrevid="229318" counter="0" length="1878">
<revisions>
<rev revid="229318" minor="" user="Savant-fou" timestamp="2009-04-25T16:07:37Z" comment="Ajout rapide de la catégorie [[:Catégorie:Accueil|Accueil]] (avec [[MediaWiki:Gadget-HotCats.js|HotCats]])" />
</revisions>
</page>
</pages>
</query>
</api>
</source>}}
 
À l'écriture de ces lignes le 17 mai 2009, le dernier réviseur de la page [[Accueil]] était {{u|Savant-fou}} - cette information est contenue dans la chaîne « user="Savant-fou" » - qui, le 25 avril 2009 à 16:07, a résumé sa modification par le commentaire « Ajout rapide de la catégorie [[:Catégorie:Accueil|Accueil]] (avec [[MediaWiki:Gadget-HotCats.js|HotCats]]) ». Pour connaître le dernier réviseur de la page d'accueil en ce moment, cliquez sur le lien ci-dessus qui affiche ce [//fr.wikibooks.org/w/api.php?action=query&prop=info|revisions&titles=Accueil&format=xml document XML].
== Réviseur de la page ==
'''1.''' Ouvrir un éditeur de texte, coller le script suivant (sans caractère spéciaux comme "é" si le fichier est en ASCII au lieu de Unicode)...
{|width=70% align=center
|{{boîte déroulante début|titre=reviseur_de_la_page.py}}
<source lang=python>
#!/usr/bin/python
# -*- coding: latin-1 -*-
# Pour Python 3, remplacez la ligne ci-dessous par import urllib.request, re
import urllib, re # import des modules a partir de la bibliotheque d'instructions de base,
nom_de_page = "Accueil" # 'urllib' pour URL library et 're' pour regular expression.
 
{{boîte déroulante début|titre=résultat de commandes dans différents formats}}
url = "http://fr.wikipedia.org/w/api.php?action=query&prop=info|revisions&titles=%s&format=xml" % nom_de_page
{{ApiEx
# affichage
| desc=XML
# Python 3 : page = urllib.request.urlopen(url)
| p1=action=query
page = urllib.urlopen(url)
| p2=titles=Albert%20Einstein
# Python 3 : infos = str(page.read(), 'utf_8')
| p3=prop=info
infos = page.read() # lit le resultat de la requete a l'url ci-dessus
| p4=format=xmlfm
page.close()
| result=<source lang="xml">
print "Les informations demandees concernant", nom_de_page, "sont les suivantes, en XML :\n\n", infos # Rajoutez des parenthèses pour Python 3 !
<?xml version="1.0" encoding="utf-8"?>
 
<api>
# extraction
<query>
print "\n...recherche l'expression rationnelle..." # Rajoutez des parenthèses pour Python 3 !
<pages>
reviseur= re.findall(' user="(.*?)" ',infos) # recherche l'expression rationnelle
<page pageid="736" ns="0" title="Albert Einstein" touched="2007-07-06T04:37:30Z" lastrevid="142335140" counter="4698" length="86906" />
print "\nDernier reviseur : ",reviseur # Rajoutez des parenthèses pour Python 3 !
</pages>
</query>
</api>
</source>
}}
{{boîte déroulante fin}}
{{ApiEx
|}
| desc=JSON
...enregistrez ce script (par exemple <code>reviseur_de_la_page.py</code>) et exécutez-le. Le script utilise [http://fr.wikipedia.org/w/api.php?action=query&prop=info|revisions&titles=Accueil&format=xmlfm cette requête] pour afficher le dernier réviseur de la page d'[[Accueil|accueil]].
| p1=action=query
 
| p2=titles=Albert%20Einstein
== Boucle réviseur bistro ==
| p3=prop=info
'''2.''' Obtenir la liste des derniers réviseurs des Bistros du mois dernier. Ouvrir l'éditeur de texte, écrire ce script utilisant plusieurs fois [http://fr.wikipedia.org/w/api.php?action=query&prop=info|revisions&titles=Accueil cette requête]... Si vous souhaitez utiliser le code suivant avec Python 3, faites les mêmes modifications que dans le script précédent. C'est-à-dire : rajoutez des parenthèses aux <code>print</code> ; chargez la classe <code>urllib.request</code> (au lieu d'<code>urllib</code> tout court) ; utilisez la fonction <code>urllib.request.urlopen</code> (au lieu de <code>urllib.urlopen</code>) ; transformez le résultat de <code>read</code> en chaîne de caractères (<code>infos = str(url.read(), 'utf_8')</code>).
| p4=format=jsonfm
{|width=70% align=center
| result=<source lang="javascript">
|{{boîte déroulante début|titre= boucle_reviseur_bistro.py}}
{
<source lang=python>
"query": {
#!/usr/bin/python
"pages": {
# -*- coding: latin-1 -*-
"736": {
import urllib, re # import des modules de la bibliotheque d'instructions fournie a l'installation.
"pageid": 736,
 
"ns": 0,
a=0
"title": "Albert Einstein",
space = ' '
"touched": "2007-07-06T04:37:30Z",
nospace = ''
"lastrevid": 142335140,
 
"counter": 4698,
while (a<31):
a = a+1 #"length": a est un nombre entier (integer)86906
}
b = str(int(a)) # et b une chaine de caractere (string)
}
nom = "Wikipedia:Le_Bistro/"+b+"_avril_2009"
}
nom = nom.replace(space, nospace) # supprime les espace
}
url = urllib.urlopen("http://fr.wikipedia.org/w/api.php?action=query" +
"&prop=info|revisions&titles=%s&format=xml" % nom )
infos = url.read()
url.close()
reviseur= re.findall(' user="(.*?)" ',infos) # recherche l'expression rationnelle
for chacun in reviseur:
print "\nDernier reviseur du bistro du",b,"avril 2009 : ",chacun
</source>
}}
{{boîte déroulante fin}}
{{ApiEx
|}
| desc=YAML
...enregistrez ce script (par exemple <code>boucle_reviseur_bistro.py</code>) et exécutez-le.
| p1=action=query
 
| p2=titles=Albert%20Einstein
== Liste des réviseurs ==
| p3=prop=info
'''3.''' La liste des réviseurs de la page d'accueil entre deux dates, et les commentaires de révisions : ouvrir l'éditeur de texte, écrire ce script, faire les mêmes modifications pour Python 3 le cas échéant... Ce script utilise [//fr.wikipedia.org/w/api.php?action=query&prop=revisions&rvstart=20090311000000&revend=20090511000000&titles=Accueil cette requête].
| p4=format=yamlfm
{|width=70% align=center
| result=<source lang="text">
|{{boîte déroulante début|titre=liste_des_reviseurs.py}}
---
<source lang=python>
query:
#!/usr/bin/python
pages:
# -*- coding: latin-1 -*-
-
import urllib, re # import des modules de la bibliotheque d'instructions fournie a l'installation.
pageid: 736
ns: 0
debut = str(int(20090311000000)) # date pour commencer a lister, ici 11 mars 2009.
title: Albert Einstein
fin = str(int(20090511000000))
touched: |
2008-03-16T04:59:39Z
nom = "Accueil"
lastrevid: 198568286
counter: 4698
url = urllib.urlopen("http://fr.wikipedia.org/w/api.php?action=query" +
length: 81076
"&prop=revisions&rvstart=%s&revend=%s&titles=%s&format=xml" % (debut, fin, nom))
infos = url.read()
url.close()
 
# recherche et affiche les reviseurs
#
reviseur= re.findall(' user="(.*?)" ',infos)
for chacun in reviseur:
print "Reviseur : ",chacun
 
# recherche et affiche les commentaires
#
commentaire= re.findall(' comment="(.*?)" ',infos)
for comment in commentaire:
print "\nCommentaire de revision : ",comment
</source>
}}
{{ApiEx
| desc=WDDX
| p1=action=query
| p2=titles=Albert%20Einstein
| p3=prop=info
| p4=format=wddxfm
| result=<source lang="xml">
<?xml version="1.0" encoding="utf-8"?>
<wddxPacket version="1.0">
<header/>
<data>
<struct>
<var name="query">
<struct>
<var name="pages">
<struct>
<var name="736">
<struct>
<var name="pageid">
<number>736</number>
</var>
<var name="ns">
<number>0</number>
</var>
<var name="title">
<string>Albert Einstein</string>
</var>
<var name="touched">
<string>2007-07-06T04:37:30Z</string>
</var>
<var name="lastrevid">
<number>142335140</number>
</var>
<var name="counter">
<number>4698</number>
</var>
<var name="length">
<number>86906</number>
</var>
</struct>
</var>
</struct>
</var>
</struct>
</var>
</struct>
</data>
</wddxPacket>
</source>
}}
{{ApiEx
| desc=PHP (serialized format, with line breaks added for readability. Use PHP's '''unserialize()''' function to recover data.)
| p1=action=query
| p2=titles=Albert%20Einstein
| p3=prop=info
| p4=format=php
| result=<source lang="text">
a:1:{s:5:"query";a:1:{s:5:"pages";a:1:{i:736;a:7:{s:6:"pageid";i:736;s:2:"ns";i:0;s:5:"title";s:15:"Albert Einstein";
s:7:"touched";s:20:"2007-07-06T04:37:30Z";s:9:"lastrevid";i:142335140;s:7:"counter";i:4698;s:6:"length";i:86906;}}}}</source>
}}
{{ApiEx
| desc=PHP (var_export format. Use PHP's '''eval()''' function to recover data.)
| p1=action=query
| p2=titles=Albert%20Einstein
| p3=prop=info
| p4=format=dbg
| result=<source lang="text">
array (
'query' =>
array (
'pages' =>
array (
736 =>
array (
'pageid' => 736,
'ns' => 0,
'title' => 'Albert Einstein',
'touched' => '2008-10-11T20:27:04Z',
'lastrevid' => 244636163,
'counter' => 4698,
'length' => 89641,
),
),
),
)
</source>
}}
{{boîte déroulante fin}}
|}
 
:::Pour aller plus loin voir : '''[[mw:API/fr]]''' ou, pour la manipuler en deux minutes, voir [[interface de Wikipédia pour programmer]].
'''Félicitations''', vous utilisez Wikipédia via son '''[[mw:API/fr|API]]''' !
 
===Google charts===
Est disponible ici : [http://chart.apis.google.com http://chart.apis.google.com/chart?]
 
Exemples d'utilisation : [http://chart.apis.google.com/chart?cht=lc&chd=t:26,35,15,28,25,18,27,28,21,29,22,29,19,21,8,23,20,27,17&chds=0,50&chm=R,E5ECF9,0,0.95,1&chs=500x400&chf=c,ls,90,999999,0.20,CCCCCC,0.20,FFFFFF,0.20,CCCCCC,0.20&chl=janvier|février|mars|avril|mai lignes] - [http://chart.apis.google.com/chart?cht=bvs&chco=C6D9FD&chd=t:26,35,15,28,25,18,27,28,21,29,22,29,19,21,8,23,20,27,17&chds=0,50&chs=500x400&chl=janvier||||février||||mars||||avril||||mai barres]
 
{{AutoCat}}
Vous pouvez poursuivre cet exercice en programmant du python sur une base vierge, ou alors utiliser [[Programmation Python/Programmer en deux minutes/l'interface de Wikipédia pour programmer/la librairie d'instructions Pywikipedia|la librairie d'instructions Pywikipedia]] et [[w:Aide:Pywikipedia|les scripts Pywikipedia hébergés par Wikimédia]]. Par exemple, vous devriez être capable de lire un script tel que :
{|width=70% align=center
|{{boîte déroulante début|titre=[http://svn.wikimedia.org/viewvc/pywikipedia/trunk/pywikipedia/statistics_in_wikitable.py?view=markup <tt>statistics_in_wikitable.py</tt>]}}
<source lang=python>
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
 
\03{lightyellow}This bot renders statistics provided by [[Special:Statistics]] in a table on a wiki page.\03{default}
Thus it creates and updates a Statistics wikitable.
 
The following parameters are supported:
 
\03{lightred}-screen\03{default} If True, doesn't do any changes, but only shows the statistics.
 
\03{lightgreen}-page\03{default} On what page statistics are rendered.
If not existing yet, it is created.
If existing, it is updated.
"""
__version__ = '$Id$'
import wikipedia, pagegenerators, query
import time
 
# This is the title of the wikipage where to render stats.
your_page = "Logstats"
 
summary_update = {
'en':u'Updating some statistics.',
}
summary_creation = {
'en':u'Creating statistics log page.',
}
 
class StatisticsBot:
def __init__ (self, screen, your_page):
"""
Constructor. Parameter:
* screen - If True, doesn't do any real changes,
but only shows some stats.
"""
self.screen = screen
self.your_page = your_page
self.dict = self.getdata() # Try to get data.
self.site = wikipedia.getSite()
 
def run(self):
if self.screen:
wikipedia.output("Bot is running to output stats.")
self.idle(1) # Run a function to idle
self.outputall()
if not self.screen:
self.outputall() # Output all datas on screen.
wikipedia.output("\nBot is running. " +
"Going to treat \03{lightpurple}%s\03{default}..." %
self.your_page )
self.idle(2)
self.treat()
 
# getdata() returns a dictionnary of the query to
# api.php?action=query&meta=siteinfo&siprop=statistics
def getdata(self):
# This method return data in a dictionnary format.
# View data with: api.php?action=query&meta=siteinfo&siprop=statistics&format=jsonfm
params = {
'action' :'query',
'meta' :'siteinfo',
'siprop' :'statistics',
}
wikipedia.output("\nQuerying api for json-formatted data...")
try:
data = query.GetData(params,self.site, encodeTitle = False)
except:
url = self.site.protocol() + '://' + self.site.hostname() + self.site.api_address()
wikipedia.output("The query has failed. Have you check the API? Cookies are working?")
wikipedia.output(u"\n>> \03{lightpurple}%s\03{default} <<" % url)
if data != None:
wikipedia.output("Extracting statistics...")
data = data['query'] # "query" entry of data.
dict = data['statistics'] # "statistics" entry of "query" dict.
return dict
 
def treat(self):
page = wikipedia.Page(self.site, self.your_page)
if page.exists():
wikipedia.output(u'\nWikitable on ' +
u'\03{lightpurple}%s\03{default} will be completed with:\n' % self.your_page )
text = page.get()
newtext = self.newraw()
wikipedia.output(newtext)
choice = wikipedia.inputChoice(
u'Do you want to add these on wikitable?', ['Yes', 'No'], ['y', 'N'], 'N')
text = text[:-3] + newtext
summ = wikipedia.translate(self.site, summary_update)
if choice == 'y':
try:
page.put(u''.join(text), summ)
except:
wikipedia.output(u'Impossible to edit. It may be an edit conflict... Skipping...')
else:
wikipedia.output(
u'\nWikitable on \03{lightpurple}%s\03{default} will be created with:\n' % self.your_page )
newtext = self.newtable()+self.newraw()
wikipedia.output(newtext)
summ = wikipedia.translate(self.site, summary_creation)
choice = wikipedia.inputChoice(
u'Do you want to accept this page creation?', ['Yes', 'No'], ['y', 'N'], 'N')
if choice == 'y':
try:
page.put(newtext, summ)
except wikipedia.LockedPage:
wikipedia.output(u"Page %s is locked; skipping." % title)
except wikipedia.EditConflict:
wikipedia.output(u'Skipping %s because of edit conflict' % title)
except wikipedia.SpamfilterError, error:
wikipedia.output(
u'Cannot change %s because of spam blacklist entry %s' % (title, error.url))
 
def newraw(self):
newtext = ('\n|----\n!\'\''+ self.date() +'\'\'') # new raw for date and stats
for name in self.dict:
newtext += '\n|'+str(abs(self.dict[name]))
newtext += '\n|----\n|}'
return newtext
 
def newtable(self):
newtext = ('\n{| class=wikitable style=text-align:center\n!'+ "date") # create table
for name in self.dict:
newtext += '\n|'+name
return newtext
 
def date(self):
return time.strftime('%Y/%m/%d', time.localtime(time.time()))
def outputall(self):
list = self.dict.keys()
list.sort()
for name in self.dict:
wikipedia.output("There are "+str(self.dict[name])+" "+name)
def idle(self, retry_idle_time):
time.sleep(retry_idle_time)
wikipedia.output(u"Starting in %i second..." % retry_idle_time)
time.sleep(retry_idle_time)
 
def main(your_page):
screen = False # If True it would not edit the wiki, only output statistics
_page = None
 
wikipedia.output("\nBuilding the bot...")
for arg in wikipedia.handleArgs(): # Parse command line arguments
if arg.startswith('-page'):
if len(arg) == 5:
_page = wikipedia.input(u'On what page do you want to add statistics?')
else:
_page = arg[6:]
if arg.startswith("-screen"):
screen = True
if not _page:
_page = your_page
if not screen:
wikipedia.output("The bot will add statistics on %s.\n" % _page )
bot = StatisticsBot(screen, _page) # Launch the instance of a StatisticsBot
bot.run() # Execute the 'run' method
 
if __name__ == "__main__":
try:
main(your_page)
finally:
wikipedia.stopme()
 
</source>
{{boîte déroulante fin}}
|}
:Le script <tt>statistics_in_wikitable.py</tt> importe quelques librairies d'instructions dont [[Programmation Python/Programmer en deux minutes/l'interface de Wikipédia pour programmer/la librairie d'instructions Pywikipedia|Pywikipedia]], définit trois variables, définit l'objet StatisticsBot, puis définit une fonction principale qui est exécutée à la fin du script (par l'instruction <tt>try: main(your_page)</tt>).
 
<noinclude>{{:Programmation Python/Programmer en deux minutes/Bas de page}}</noinclude>