Command disabled: edit
 
Table of Contents

1

Nous allons utiliser le module socket.

python

 1: import socket
 2:
 3: HOST = 'listes.example.com'    # Le serveur
 4: PORT = 80                      # Le port
 5: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 6: s.connect((HOST, PORT))
 7: s.sendall('''GET /anfexo/plm.html HTTP/1.1
 8: Host: listes.example.com
 9:
10: ''')
11: page=''
12: while True:
13:     suite=s.recv(1024)
14:     if suite:
15:         page=page+suite
16:     else:
17:         break
18: s.close()
19: print page

page contient toute la réponse du serveur : la ligne de statut (200 OK), les en-têtes et le corps du message. Aucun découpage/analyse de la réponse n'est effectuée.

2a

Voici un module spécialisé dans les requètes HTTP : httplib.

python

 1: import httplib
 2:
 3: conn = httplib.HTTPConnection("listes.example.com")
 4: conn.request("GET", "/anfexo/plm.html")
 5: r1 = conn.getresponse()
 6:
 7: print "code: %s - message: %s"%(r1.status,r1.reason)
 8: print "header: content-type: %s"%r1.getheader("content-type")
 9: print "header: server: %s"%r1.getheader("server")
10: print "content: %s"%r1.read()

2b

Nous allons utiliser le module urllib.

python

1: import urllib
2:
3: f=urllib.urlopen('http://listes.example.com/anfexo/plm.html')
4: print "code: %s"%f.getcode()
5: print "header: content-type: %s"%f.headers.getheader('content-type')
6: print "header: server: %s"%f.headers.getheader('server')
7: print "content: %s"%f.read()

2c

Nous allons utiliser ici un module un peu plus évolué : urllib2.

python

 1: import urllib2
 2: import sys
 3:
 4: try:
 5:     f=urllib2.urlopen('http://listes.example.com/anfexo/plm.html')
 6: except urllib2.HTTPError, e:
 7:     print "Erreur ",e.code
 8:     print e.read()
 9:     sys.exit(1)
10: except urllib2.URLError, e:
11:     print 'Erreur de connexion'
12:     print 'Raison: ', e.reason
13:     sys.exit(2)
14:
15: print "code: %s"%f.getcode()
16: print "header: content-type: %s"%f.headers.getheader('content-type')
17: print "header: server: %s"%f.headers.getheader('server')
18: print "content: %s"%f.read()

3

Nous allons utiliser lxml pour extraire un formulaire de la réponse reçue, le remplir, le soumettre et consulter le retour.

python

 1: import lxml
 2: import lxml.html
 3:
 4: doc=lxml.html.parse("http://listes.example.com/cgi-bin/form.cgi").getroot()
 5:
 6: form=doc.forms[0]
 7: form.fields['nom']='aicardi'
 8: form.fields['prenom']='stephane'
 9: form.fields['email']='stephane.aicardi@cnrs.math.fr'
10:
11: result = lxml.html.submit_form(form)
12:
13: print "code: %s"%result.getcode()
14: print "content: %s"%result.read()
mercredi_corrige_python_2.txt · Last modified: 2012/05/12 17:00 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki