Pregunta

Actualmente tengo un pequeño script que descarga una página web y extrae algunos datos que me interesan. Nada interesante.

Actualmente estoy descargando la página así:

import commands
command = 'wget --output-document=- --quiet --http-user=USER --http-password=PASSWORD https://www.example.ca/page.aspx'
status, text = commands.getstatusoutput(command)

Aunque esto funciona perfectamente, pensé que tendría sentido eliminar la dependencia de wget. Pensé que debería ser trivial convertir lo anterior a urllib2, pero hasta ahora no he tenido éxito. Internet es un ejemplo completo de urllib2, pero no he encontrado nada que coincida con mi necesidad de autenticación HTTP simple de nombre de usuario y contraseña con un servidor HTTPS.

¿Fue útil?

Solución

El módulo request proporciona una API moderna para las capacidades HTTP / HTTPS.

import requests

url = 'https://www.someserver.com/toplevelurl/somepage.htm'

res = requests.get(url, auth=('USER', 'PASSWORD'))

status = res.status_code
text   = res.text

Otros consejos

esto dice que debería ser sencillo

  

[as] siempre que su Python local tenga soporte SSL.

Si usa solo la autenticación básica HTTP, debe configurar un controlador diferente, como se describe aquí .

Citando el ejemplo allí:

import urllib2

theurl = 'http://www.someserver.com/toplevelurl/somepage.htm'
username = 'johnny'
password = 'XXXXXX'
# a great password

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, theurl, username, password)
# because we have put None at the start it will always
# use this username/password combination for  urls
# for which `theurl` is a super-url

authhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandler

opener = urllib2.build_opener(authhandler)

urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler
# Make sure not to include the protocol in with the URL, or
# HTTPPasswordMgrWithDefaultRealm will be very confused.
# You must (of course) use it when fetching the page though.

pagehandle = urllib2.urlopen(theurl)
# authentication is now handled automatically for us

Si haces Digest, tendrás que configurar algunos encabezados adicionales, pero son los mismos independientemente del uso de SSL. Google para python + urllib2 + http + digest.

Saludos,

La documentación de urllib2 tiene un ejemplo de trabajo con autenticación básica:

http://docs.python.org/library/urllib2.html#examples

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top