[pyar] obtener datos de afip(servicios interactivos, no webservice) desde python

Diego s myqp2010 en gmail.com
Sab Mar 31 15:35:52 ART 2012


Hola, consulto porque estoy intentando hacer lo del asunto y no encuentro cómo.
Lo que quiero es entrar a servicios con clave fiscal de afip, abrir el
servicio(ddjj, cuenta tributaria, etc) y descargar la info a una
planilla para trabajarla.
tengo problemas para la autenticación, sigo los ejemplos que hay en la
web pero siempre me sale nombre de usuario o contraseña incorrectos.
quizá la página tenga algún tipo de seguridad que prevenga el login
automático o mas probable es que estoy haciendo todo mal.
con mechanize logro completar el formulario de login sin problemas
pero cuando quiero abrir alguno de los link que me aparece me sale el
error de autenticación, seguramente tengo que guardar alguna cookie no
se. con urllib-urllib2 no logro conseguir la autenticación.
aclaro que soy contador no informático y si bien escribo macros en
oobasic no tengo conocimientos de lenguajes de programación(si bien
logre hacer esto en python pero en pág que n requieren user y
pass,jeje)
No se si influye pero probe en ubuntu 10.04 y fedora 16 sin éxito.

estos son los cod que uso:

con mechanize:

import re
import mechanize
import cookielib

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

# Want debugging messages?
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)

# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686;
en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9
Firefox/3.0.1')]


# Open some site, let's pick a random one, the first that pops in mind:
#br.add_password('https://auth.afip.gov.ar/contribuyente/', 'cuit', 'clave')
r = br.open('https://auth.afip.gov.ar/contribuyente/')
html = r.read()

# Show the source
#print html
# or
#print br.response().read()

for form in br.forms():
	print form

# Select the first (index zero) form
br.select_form(nr=0)

# Let's search
br.form['user']= "n° de cuit"
br.form['password']='clave fiscal'
br.submit()
print br.response().read()


ESTE CON URLLIB:

import re
import mechanize
import cookielib
import urllib2


import urllib
opener = urllib.FancyURLopener()


# Cookie Jar
cj = cookielib.LWPCookieJar()
#opener.set_cookiejar(cj)

# Browser options
#opener.set_handle_equiv(True)
#opener.set_handle_gzip(True)
#opener.set_handle_redirect(True)
#opener.set_handle_referer(True)
#opener.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
#br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

# Want debugging messages?
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)

# User-Agent (this is cheating, ok?)
opener.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686;
en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9
Firefox/3.0.1')]


page = opener.open('https://CUIT:CLAVE@auth.afip.gov.ar/contribuyente/').read()
#print page




INCLUSO CORRO ESTO QUE ENCONTRE POR AHI Y ME SALE QUE LA PAG NO
REQUIERE AUTENTICACION¿?¡¿?

import urllib2, sys, re, base64
from urlparse import urlparse
#theurl = 'https://auth.afip.gov.ar/contribuyente/'
theurl = "https://seti.afip.gob.ar/setiweb/presentacion/presentacion.jsp"
print "N° de cuit"
username = raw_input()
print "ponela"
password = raw_input()

req = urllib2.Request(theurl)
try:
    handle = urllib2.urlopen(req)
    print req
    print urllib2.Request(theurl)
except IOError, e:                  # here we are assuming we fail
    pass
else:                               # If we don't fail then the page
isn't protected
    print "This page isn't protected by authentication."
    sys.exit(1)

if not hasattr(e, 'code') or e.code != 401:                 # we got
an error - but not a 401 error
    print "This page isn't protected by authentication."
    print 'But we failed for another reason.'
    sys.exit(1)

authline = e.headers.get('www-authenticate', '')                # this
gets the www-authenticat line from the headers - which has the
authentication scheme and realm in it
if not authline:
    print 'A 401 error without an authentication response header - very weird.'
    sys.exit(1)

authobj = re.compile(r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"](\w+)['"]''',
re.IGNORECASE)          # this regular expression is used to extract
scheme and realm
matchobj = authobj.match(authline)
if not matchobj:                                        # if the
authline isn't matched by the regular expression then something is
wrong
    print 'The authentication line is badly formed.'
    sys.exit(1)
scheme = matchobj.group(1)
realm = matchobj.group(2)
if scheme.lower() != 'basic':
    print 'This example only works with BASIC authentication.'
    sys.exit(1)

base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader =  "Basic %s" % base64string
req.add_header("Authorization", authheader)
try:
    handle = urllib2.urlopen(req)
except IOError, e:                  # here we shouldn't fail if the
username/password is right
    print "It looks like the username or password is wrong."
    sys.exit(1)
thepage = handle.read()

server = urlparse(theurl)[1].lower()            # server names are
case insensitive, so we will convert to lower case
test = server.find(':')
if test != -1: server = server[:test]           # remove the :port
information if present, we're working on the principle that realm
names per server are likely to be unique...

passdict = {(server, realm) : authheader }      # now if we get
another 401 we can test for an entry in passdict before having to ask
the user for a username/password

print 'Done successfully - information now stored in passdict.'
print 'The webpage is stored in thepage.'


Alguna guia al repecto? gracias de antemano. saludos



More information about the pyar mailing list