Full Code of henriquebastos/itauscraper for AI

master eed27f360516 cached
13 files
28.9 KB
7.7k tokens
37 symbols
1 requests
Download .txt
Repository: henriquebastos/itauscraper
Branch: master
Commit: eed27f360516
Files: 13
Total size: 28.9 KB

Directory structure:
gitextract_tvmfx8bg/

├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.rst
├── itauscraper/
│   ├── __init__.py
│   ├── __main__.py
│   ├── cli.py
│   ├── converter.py
│   ├── itertools.py
│   ├── pages.py
│   └── scraper.py
├── requirements.txt
└── setup.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# dotenv
.env

# virtualenv
.venv
venv/
ENV/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/

.idea/
.DS_Store


================================================
FILE: LICENSE
================================================
                   GNU LESSER GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.


  This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.

  0. Additional Definitions.

  As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.

  "The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.

  An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.

  A "Combined Work" is a work produced by combining or linking an
Application with the Library.  The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".

  The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.

  The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.

  1. Exception to Section 3 of the GNU GPL.

  You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.

  2. Conveying Modified Versions.

  If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:

   a) under this License, provided that you make a good faith effort to
   ensure that, in the event an Application does not supply the
   function or data, the facility still operates, and performs
   whatever part of its purpose remains meaningful, or

   b) under the GNU GPL, with none of the additional permissions of
   this License applicable to that copy.

  3. Object Code Incorporating Material from Library Header Files.

  The object code form of an Application may incorporate material from
a header file that is part of the Library.  You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:

   a) Give prominent notice with each copy of the object code that the
   Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the object code with a copy of the GNU GPL and this license
   document.

  4. Combined Works.

  You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:

   a) Give prominent notice with each copy of the Combined Work that
   the Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the Combined Work with a copy of the GNU GPL and this license
   document.

   c) For a Combined Work that displays copyright notices during
   execution, include the copyright notice for the Library among
   these notices, as well as a reference directing the user to the
   copies of the GNU GPL and this license document.

   d) Do one of the following:

       0) Convey the Minimal Corresponding Source under the terms of this
       License, and the Corresponding Application Code in a form
       suitable for, and under terms that permit, the user to
       recombine or relink the Application with a modified version of
       the Linked Version to produce a modified Combined Work, in the
       manner specified by section 6 of the GNU GPL for conveying
       Corresponding Source.

       1) Use a suitable shared library mechanism for linking with the
       Library.  A suitable mechanism is one that (a) uses at run time
       a copy of the Library already present on the user's computer
       system, and (b) will operate properly with a modified version
       of the Library that is interface-compatible with the Linked
       Version.

   e) Provide Installation Information, but only if you would otherwise
   be required to provide such information under section 6 of the
   GNU GPL, and only to the extent that such information is
   necessary to install and execute a modified version of the
   Combined Work produced by recombining or relinking the
   Application with a modified version of the Linked Version. (If
   you use option 4d0, the Installation Information must accompany
   the Minimal Corresponding Source and Corresponding Application
   Code. If you use option 4d1, you must provide the Installation
   Information in the manner specified by section 6 of the GNU GPL
   for conveying Corresponding Source.)

  5. Combined Libraries.

  You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:

   a) Accompany the combined library with a copy of the same work based
   on the Library, uncombined with any other library facilities,
   conveyed under the terms of this License.

   b) Give prominent notice with the combined library that part of it
   is a work based on the Library, and explaining where to find the
   accompanying uncombined form of the same work.

  6. Revised Versions of the GNU Lesser General Public License.

  The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.

  Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.

  If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.


================================================
FILE: MANIFEST.in
================================================
include *.rst *.txt LICENSE


================================================
FILE: README.rst
================================================
Itaú Scraper
============

Scraper para baixar seus extratos do Itaú com um comando.

Motivação
---------

As APIs vieram para ficar, mas a maioria dos bancos ainda não oferecem forma
fácil para seus clientes extraírem seus próprios dados. Algo tão simples
quanto obter o seu extrato bancário é um sofrimento para sistematizar.

Pesquisei se existia algo pronto para o Itaú e encontrei o
`bankscraper <https://github.com/kamushadenes/bankscraper>`_ do
`Kamus <http://endurance.hyadesinc.com/>`_ que disponibiliza vários scripts
interessantes. Infelizmente o do Itaú não estava mais funcionando,
mas estudando seu código encontrei uma boa dica:

    O site do Itaú para computador é todo complicado para navegar com muita
    mágica em javascript. Mas e o site para disponsitivos móveis?

Ativei o `"mobile mode" <https://developers.google.com/web/tools/chrome-devtools/device-mode/>`_
do Chrome com o `Postman <https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop>`_
e o `Postman Interceptor <https://chrome.google.com/webstore/detail/postman-interceptor/aicmkgpgakddgnaphhhpliifpcfhicfo>`_
para rastrear todas as requisições e **bingo**. De fato é bem mais simples.

Decidi escrever este artigo para explicar o procedimento, evidenciar as
bizarrices e quem sabe facilitar a manutenção futura quando algo mudar.

Este script funciona apenas para contas *Pessoa Física*, pois o Itaú força
empresas a usarem seu aplicativo no celular não dando acesso ao site móvel
pelo navegador.

Como funciona
~~~~~~~~~~~~~

O código é simples e usa `Python 3 <https://www.python.org/>`_ com a biblioteca
`requests <http://docs.python-requests.org/en/master/>`_ para a navegação
e `lxml <http://lxml.de/>`_ para a extração de dados com
`xpath <http://ricostacruz.com/cheatsheets/xpath.html>`_.

Mais do que explicar o código em si, o importante é entender o fluxo de
navegação que ele precisa reproduzir.

O protocolo HTTP é *assíncrono* exigindo que cada requisição envie novamente
todas as informações necessárias. No entanto, o site do banco cria uma dinâmica
cliente-servidor estabelecendo dependência entre as requisições mudando inclusive
as urls de navegação. Por isso todo o processo acontece sequencialmente, cheio de
etapas intermediárias que não seriam necessárias em condições normais.

Usando o ``requests.Session`` conseguimos reproduzir o efeito de navegação contínua
entre várias páginas propagando *cookies* e outros *cabeçalhos*.

A classe ``MobileSession`` implementa os cabeçalhos para nos fazermos
passar por um browser de celular.

A classe ``ItauScraper`` usa a ``session`` para realizar o ``login`` e
consultar o ``extrato``.

O login
~~~~~~~

Para fazer o ``login`` no site do banco é preciso acessar uma url inicial para
descobrirmos a url de login real, que muda de tempos em tempos pelo que eu entendi.

Com a *url de login* correta, agora é preciso fazer um novo ``GET`` para obter
informações que o ASP.NET injeta no formulário de login e então realizar o POST
efetuando a autenticação.

Depois do login feito, somos redirecionados para uma página com um menu de
navegação. Esta página não é usada no fluxo, mas quando quisermos implementar novas
funcionalidades no ``ItauScraper`` é nela que deveremos começar.

.. image:: https://raw.githubusercontent.com/henriquebastos/itauscraper/master/docs/itau-login.jpg

O extrato
~~~~~~~~~

Quando acessamos a *url do extrato*, por padrão é exibido o extrato dos *últimos 3 dias*.
No fim da página do extrato tem 4 links para listar os extratos dos períodos
7, 15, 30 e 90 dias. Estas urls parecem mudar de tempos em tempos, como a do login,
então é preciso *extrair o link* para *90 dias* e obter o extrato com outro ``GET``.

.. image:: https://raw.githubusercontent.com/henriquebastos/itauscraper/master/docs/itau-extrato.jpg

Com o extrato do maior período:

1. Extraímos a informação do html;
2. Reconstruímos a tabela com as colunas: data, descrição e valor;
3. Filtramos as linhas de saldo que não correspondem a um lançamento;
4. Convertemos cada *data* para o tipo ``datetime.date``;
5. Convertemos cada *valor* para o tipo ``Decimal``;

No final, temos uma *tupla de tuplas* na forma:

.. code-block:: python

    ((datetime.date(2017, 1, 1), 'RSHOP-LOJA1', Decimal('-1.99')),
     (datetime.date(2017, 1, 2), 'RSHOP-LOJA2', Decimal('-5.00')),
     (datetime.date(2017, 1, 3), 'TBI 1234567', Decimal('10.00')))

O cartão
~~~~~~~~

Quando acessamos a *url do cartão*, são exibidas 3 opções para listar:

1. a fatura anterior;
2. a fatura atual;
3. os lançamentos parciais da próxima fatura.

Estas urls parecem mudar de tempos em tempos, então é preciso *extrair o link* para a *fatura atual*
e realizar um novo ``GET`` para obter o extrato de lançamentos.

.. image:: https://raw.githubusercontent.com/henriquebastos/itauscraper/master/docs/itau-cartao.jpg

Além dos lançamentos, há na página um resumo com totais.

Com o extrato do cartão:

1. Extraímos a informação do html;
2. Reconstruímos o resumo como um *dicionário*.
3. Reconstruímos a tabela com as colunas: data, descrição e valor;
4. Convertemos cada *data* para o tipo ``datetime.date``;
5. Convertemos cada *valor* para o tipo ``Decimal``;

No final, temos um *dicionário* com o sumário da fatura e uma *tupla de tuplas* na forma:

.. code-block:: python

    # sumário
    {'Total dos lançamentos anteriores': Decimal('4.99'),
     'Créditos e pgtos': Decimal('4.99'),
     'Total nacional': Decimal('1.99'),
     'Total internacional': Decimal('0.00'),
     'Dólar em 06/07/2017': Decimal('9.99'),
     'Total dos lançamentos atuais': Decimal('1.99'),
     'Pagamento mínimo': Decimal('0.25')}

    # lançamentos
    ((datetime.date(2017, 1, 1), 'RSHOP-LOJA1', Decimal('-1.99')),
     (datetime.date(2017, 1, 2), 'RSHOP-LOJA2', Decimal('-5.00')),
     (datetime.date(2017, 1, 3), 'TBI 1234567', Decimal('10.00')))

Como usar
---------

Use pela linha de comando:

.. code-block:: console

 $ itauscraper --extrato --cartao --agencia 1234 --conta 12345 --digito 6
 Digite sua senha do Internet Banking: 


Ou:

.. code-block:: console

 $ itauscraper --extrato --cartao --agencia 1234 --conta 12345 --digito 6 --senha SECRET


Ou importe direto no seu código:

.. code-block:: python

 from itauscraper import ItauScraper

 itau = ItauScraper(agencia='1234', conta='12345', digito='6', senha='SECRET')
 itau.login():
 print(itau.extrato())
 print(itau.cartao())
 # TODO: Divirta-se!

Para conhecer todas as opções execute:

.. code-block:: console

 $ itauscraper -h


Development
-----------

.. code-block:: console

 git clone https://github.com/henriquebastos/itauscraper.git
 cd itauscraper
 python -m venv -p python3.6 .venv
 source .venv/bin/activate
 pip install -r requirements.txt


Licença
-------

Copyright (C) 2017 Henrique Bastos.

Este código é distribuído nos termos da "GNU LGPLv3". Veja o arquivo LICENSE para detalhes.


================================================
FILE: itauscraper/__init__.py
================================================
from itauscraper.scraper import ItauScraper


================================================
FILE: itauscraper/__main__.py
================================================
from itauscraper import cli

cli.main()


================================================
FILE: itauscraper/cli.py
================================================
"""Command line interface."""
import argparse

from getpass import getpass
from tabulate import tabulate

from itauscraper.scraper import ItauScraper


def csv(data):
    lines = (','.join((str(col) for col in row)) for row in data)
    return '\n'.join(lines)


def table(data):
    return tabulate(data, floatfmt='.2f')


def main():
    parser = argparse.ArgumentParser(prog='itau',
                                     description='Scraper para baixar seus extratos do Itaú com um comando.')

    parser.add_argument('--extrato', action='store_true', help='Lista extrato da conta corrente.')
    parser.add_argument('--cartao', action='store_true', help='Lista extrato do cartão de crédito.')
    parser.add_argument('--agencia', '-a', help='Agência na forma 0000', required=True)
    parser.add_argument('--conta', '-c', help='Conta sem dígito na forma 00000', required=True)
    parser.add_argument('--digito', '-d', help='Dígito da conta na forma 0', required=True)
    parser.add_argument('--senha', '-s', help='Senha eletrônica da conta no Itaú.')
    parser.add_argument('--csv', help='Imprime os dados em CSV.', dest='output',
                        action='store_const', const=csv, default=table)

    args = parser.parse_args()

    if not (args.extrato or args.cartao):
        parser.exit(0, "Indique a operação: --extrato e/ou --cartao\n")

    output = args.output  # csv or table (default)
    senha = args.senha or getpass("Digite sua senha do Internet Banking: ")

    itau = ItauScraper(args.agencia, args.conta, args.digito, senha)

    assert itau.login()

    if args.extrato:
        data = itau.extrato()
        print()
        print(output(data))

    if args.cartao:
        summary, data = itau.cartao()
        print()
        print(output(summary.items()))
        print()
        print(output(data))


================================================
FILE: itauscraper/converter.py
================================================
"""Funções de conversão usada pelo scraper do Itaú."""
import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from decimal import Decimal


def date(s):
    """Converte strings 'DD/MM' em datetime.date.
    Leva em consideração ano anterior para meses maiores que o mês corrente.
    """
    dt = parse(s, dayfirst=True)

    # Se o mês do lançamento > mês atual, o lançamento é do ano passado.
    if dt.month > datetime.date.today().month:
        dt += relativedelta(years=-1)

    dt = dt.date()

    return dt


def decimal(s):
    """Converte strings para Decimal('-9876.54').
    >>> assert decimal('9.876,54-') == Decimal('-9876.54')
    >>> assert decimal('9.876,54 D') == Decimal('-9876.54')
    >>> assert decimal('9.876,54 C') == Decimal('9876.54')
    >>> assert decimal('R$ 9.876,54') == Decimal('9876.54')
    >>> assert decimal('R$ -9.876,54') == Decimal('-9876.54')
    """
    s = s.replace('.', '')
    s = s.replace(',', '.')

    if s.startswith('R$ '):
        s = s[3:]

    if s.endswith('-'):
        s = s[-1] + s[:-1]
    elif s.endswith(' D'):
        s = '-' + s[:-2]
    elif s.endswith(' C'):
        s = s[:-2]

    return Decimal(s)


def is_balance(s):
    """Retorna True quando s é uma entrada de saldo em vez de lançamento."""
    return s in ('S A L D O',
                 '(-) SALDO A LIBERAR',
                 'SALDO FINAL DISPONIVEL',
                 'SALDO ANTERIOR')


def statements(iterable):
    """Converte dados do extrato de texto para tipos Python.
    Linhas de saldo são ignoradas.
    Entrada: (('21/07', 'Lançamento', '9.876,54-'), ...)
    Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...)
    """
    return ((date(a), b, decimal(c)) for a, b, c in iterable if not is_balance(b))


def card_statements(iterable):
    """Converte dados do extrato do cartão de texto para tipos Python.
    Entrada: (('21/07', 'Lançamento', '9.876,54 D'), ...)
    Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...)
    """
    return ((date(a), b, decimal(c)) for a, b, c in iterable)


def card_summary(iterable):
    """Converte dados do resumo do cartão de texto para tipos Python.
    Entrada: (('Item do Resumo', 'R$ -9.876,54'), ...)
    Saída..: (('Item do Resumo', Decimal('-9876.54')), ...)
    """
    return ((a, decimal(b)) for a, b in iterable)


================================================
FILE: itauscraper/itertools.py
================================================
"""Itertools recipies from Python documentation."""


def grouper(iterable, size=2):
    """
    Collect data into fixed-length chunks or blocks.
    grouper('ABCDEFGHI', 3) --> ABC DEF GHI
    """
    return zip(*[iter(iterable)] * size)


================================================
FILE: itauscraper/pages.py
================================================
"""Classes que sabem extrair conteúdos das páginas do Itaú."""
from lxml import html

from itauscraper.converter import card_statements, card_summary, statements
from itauscraper.itertools import grouper


class Page:
    """Classe base usada para extrair informações relevantes do Itaú."""

    def __init__(self, response):
        self.response = response
        self.tree = html.fromstring(response.content)

    def is_authenticated(self):
        return b"autenticado = 'S'" in self.response.content


class FirstPage(Page):
    """Página inicial de onde extrairemos a url de login válida."""

    def valid_login_url(self):
        # Extrai do html o parâmetro de sessão e anexa à url de login.
        url = 'https://ww70.itau.com.br/M/LoginPF.aspx'

        nl = self.tree.xpath("//a[starts-with(@href, '../Login')]/@href")
        href = nl[-1]
        param = href.split('?')[-1]
        url = ''.join((url, '?', param))
        return url


class LoginPage(Page):
    """Página de login de onde extraímos o formulário de autenticação."""

    def formdata(self, agencia, conta, digito, senha):
        # Extrai os nomes e valores dos campos do ASP.NET montando um dicionário.
        xpath = "//input[starts-with(@name, '__') and @value]/@*[name()='name' or name()='value']"
        viewstate = dict(grouper(self.tree.xpath(xpath)))

        # Prepara o dicionário com dados do post combinado os dados do ASP.NET e os dados da conta.
        data = {}
        data.update(viewstate)
        data.update({
            'ctl00$ContentPlaceHolder1$txtAgenciaT': agencia,
            'ctl00$ContentPlaceHolder1$txtContaT': conta,
            'ctl00$ContentPlaceHolder1$txtDACT': digito,
            'ctl00$ContentPlaceHolder1$txtPassT': senha,
            'ctl00$ContentPlaceHolder1$btnLogInT.x': '12',
            'ctl00$ContentPlaceHolder1$btnLogInT.y': '14',
            'ctl00$hddAppTokenApp': '',
            'ctl00$hddExisteApp': '',
        })

        return data


class MenuPage(Page):
    """Página com o menu de navegação do site do Itaú de onde extraímos as urls válidas."""

    def url_cartao(self):
        # Extrai do html a url das faturas do cartão.
        nl = self.tree.xpath("//span[.='Cartões']/ancestor::div[1]/a/@href")
        url = nl[-1]
        return url


class StatementPage(Page):
    def url_max_period(self):
        # Extrai do html o parâmetro da url para a listagem dos últimos 90 dias e anexa à url do extrato.
        url = 'https://ww70.itau.com.br/M/SaldoExtratoLancamentos.aspx'
        nl = self.tree.xpath("//a[starts-with(@href, 'Saldo')]/@href")
        href = nl[-1]
        param = href.split('?')[-1]
        url = ''.join((url, '?', param))
        return url

    def statements(self):
        # Extrai do html os lançamentos e transforma em
        xpath = "//fieldset[@id='ctl00_ContentPlaceHolder1_FieldExtratoTouch']//td[string-length(text())>1]/text()"
        nl = self.tree.xpath(xpath)
        data = tuple(grouper(nl, size=3))  # Reconstroi a tabela de 3 em 3.
        rows = data[1:]  # Ignora o cabeçalho da tabela.
        stmts = tuple(statements(rows))  # Converte textos para tipos Python
        return stmts


class CardMenuPage(Page):
    BASE_URL = 'https://ww70.itau.com.br/M/FaturaCartaoCreditoQT.aspx'

    def _url_menu(self, text):
        nl = self.tree.xpath("//div[.='Lançamentos {}']/ancestor::div[1]/a/@href".format(text))
        href = nl[-1]
        param = href.split('?')[-1]
        url = ''.join((self.BASE_URL, '?', param))
        return url

    def url_menu_current(self):
        return self._url_menu('atuais')

    def url_menu_previous(self):
        return self._url_menu('anteriores')

    def url_menu_next(self):
        return self._url_menu('futuros')


class CardStatement(Page):
    def summary(self):
        xpath = "//table[@id='ctl00_ContentPlaceHolder1_tbResumoTableT']//td/text()"
        nl = self.tree.xpath(xpath)
        rows = tuple(grouper(nl, size=2))  # Reconstroi a tabela de 2 em 2.
        return dict(card_summary(rows))  # Converte textos para tipos Python

    def statements(self):
        # Extrai do html os lançamentos do cartão.
        xpath = "//table[@id='ctl00_ContentPlaceHolder1_tbmovnacionalT']//*[@class='saldo']//td/text()"
        nl = self.tree.xpath(xpath)
        data = tuple(grouper(nl, size=3))  # Reconstroi a tabela de 3 em 3.
        rows = data[1:]  # Ignora o lançamento de pagamento anterior.
        stmts = tuple(card_statements(rows))  # Converte textos para tipos Python
        return stmts


================================================
FILE: itauscraper/scraper.py
================================================
"""Lógica do navegação no site do Itaú."""
import requests

from itauscraper.pages import CardMenuPage, StatementPage, MenuPage, LoginPage, FirstPage, CardStatement


class MobileSession(requests.Session):
    """Session customizado para se passar por navegador de dispositivo móvel."""

    def __init__(self):
        super().__init__()

        self.headers.update({
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36',
            'Accept': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4',
        })


class ItauScraper:
    """Scraper do Itaú Pessoa Física."""

    def __init__(self, agencia, conta, digito, senha):
        self.agencia = agencia
        self.conta = conta
        self.digito = digito
        self.senha = senha

        self.session = MobileSession()

    def login(self):
        url = 'https://ww70.itau.com.br/M/LoginPF.aspx'

        # Faz um GET na url inválida de login para descobrir o parâmetro de sessão.
        response = self.session.get(url)
        page = FirstPage(response)

        url = page.valid_login_url()

        # Faz um GET na url válida de login para exibir o formulário com campos do ASP.NET.
        response = self.session.get(url)
        page = LoginPage(response)

        # Faz o POST realizando o login.
        data = page.formdata(self.agencia, self.conta, self.digito, self.senha)
        response = self.session.post(url, data=data)
        page = MenuPage(response)

        return page

    def extrato(self):
        url = 'https://ww70.itau.com.br/M/SaldoExtratoLancamentos.aspx'

        # Assumindo que estamos logados, faz um GET na url que lista os lançamentos.
        # Por padrão serão mostrados lançamentos realizados nos últimos 3 dias.
        response = self.session.get(url)
        page = StatementPage(response)

        url = page.url_max_period()

        # Faz um GET para listar os lançamentos dos últimos 90 dias, que é o maior período possível.
        response = self.session.get(url)
        page = StatementPage(response)

        stmts = page.statements()

        return stmts

    def cartao(self):
        url = 'https://ww70.itau.com.br/M/FaturaCartaoCreditoQT.aspx'

        # Assumindo que estamos logados, faz um GET na url que lista o menu do cartão.
        response = self.session.get(url)
        page = CardMenuPage(response)

        # Faz um GET para listar os lançåmentos atuais do cartão.
        url = page.url_menu_current()
        response = self.session.get(url)
        page = CardStatement(response)

        summary = page.summary()
        stmts = page.statements()

        return summary, stmts



================================================
FILE: requirements.txt
================================================
lxml==3.8.0
python-dateutil==2.6.1
requests==2.18.1
tabulate==0.7.7


================================================
FILE: setup.py
================================================
# coding: utf-8
from setuptools import setup
import os


README = os.path.join(os.path.dirname(__file__), 'README.rst')
REQUIREMENTS = os.path.join(os.path.dirname(__file__), 'requirements.txt')


if __name__ == "__main__":
    setup(name='itauscraper',
          description='Scraper para baixar seus extratos do Itaú com um comando.',
          version='1.0',
          long_description=open(README).read(),
          author="Henrique Bastos", author_email="henrique@bastos.net",
          license="GNU LGPLv3",
          url='http://github.com/henriquebastos/itauscraper/',
          keywords=['scraper', 'requests', 'lxml', 'itau', 'bank', 'finance', 'accounting'],
          install_requires=open(REQUIREMENTS).readlines(),
          packages=['itauscraper'],
          package_dir={"itauscraper": "itauscraper"},
          entry_points={
              'console_scripts': [
                  'itauscraper = itauscraper.cli:main',
              ]
          },
          zip_safe=False,
          platforms='any',
          include_package_data=True,
          classifiers=[
              'Development Status :: 5 - Production/Stable',
              'Environment :: Console',
              'Intended Audience :: Financial and Insurance Industry',
              'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
              'Natural Language :: Portuguese (Brazilian)',
              'Programming Language :: Python :: 3.4',
              'Programming Language :: Python :: 3.5',
              'Programming Language :: Python :: 3.6',
              'Programming Language :: Python :: 3 :: Only',
              'Topic :: Office/Business :: Financial :: Accounting',
              'Topic :: Utilities',
          ])
Download .txt
gitextract_tvmfx8bg/

├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.rst
├── itauscraper/
│   ├── __init__.py
│   ├── __main__.py
│   ├── cli.py
│   ├── converter.py
│   ├── itertools.py
│   ├── pages.py
│   └── scraper.py
├── requirements.txt
└── setup.py
Download .txt
SYMBOL INDEX (37 symbols across 5 files)

FILE: itauscraper/cli.py
  function csv (line 10) | def csv(data):
  function table (line 15) | def table(data):
  function main (line 19) | def main():

FILE: itauscraper/converter.py
  function date (line 8) | def date(s):
  function decimal (line 23) | def decimal(s):
  function is_balance (line 47) | def is_balance(s):
  function statements (line 55) | def statements(iterable):
  function card_statements (line 64) | def card_statements(iterable):
  function card_summary (line 72) | def card_summary(iterable):

FILE: itauscraper/itertools.py
  function grouper (line 4) | def grouper(iterable, size=2):

FILE: itauscraper/pages.py
  class Page (line 8) | class Page:
    method __init__ (line 11) | def __init__(self, response):
    method is_authenticated (line 15) | def is_authenticated(self):
  class FirstPage (line 19) | class FirstPage(Page):
    method valid_login_url (line 22) | def valid_login_url(self):
  class LoginPage (line 33) | class LoginPage(Page):
    method formdata (line 36) | def formdata(self, agencia, conta, digito, senha):
  class MenuPage (line 58) | class MenuPage(Page):
    method url_cartao (line 61) | def url_cartao(self):
  class StatementPage (line 68) | class StatementPage(Page):
    method url_max_period (line 69) | def url_max_period(self):
    method statements (line 78) | def statements(self):
  class CardMenuPage (line 88) | class CardMenuPage(Page):
    method _url_menu (line 91) | def _url_menu(self, text):
    method url_menu_current (line 98) | def url_menu_current(self):
    method url_menu_previous (line 101) | def url_menu_previous(self):
    method url_menu_next (line 104) | def url_menu_next(self):
  class CardStatement (line 108) | class CardStatement(Page):
    method summary (line 109) | def summary(self):
    method statements (line 115) | def statements(self):

FILE: itauscraper/scraper.py
  class MobileSession (line 7) | class MobileSession(requests.Session):
    method __init__ (line 10) | def __init__(self):
  class ItauScraper (line 21) | class ItauScraper:
    method __init__ (line 24) | def __init__(self, agencia, conta, digito, senha):
    method login (line 32) | def login(self):
    method extrato (line 52) | def extrato(self):
    method cartao (line 70) | def cartao(self):
Condensed preview — 13 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (31K chars).
[
  {
    "path": ".gitignore",
    "chars": 1175,
    "preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
  },
  {
    "path": "LICENSE",
    "chars": 7651,
    "preview": "                   GNU LESSER GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007"
  },
  {
    "path": "MANIFEST.in",
    "chars": 28,
    "preview": "include *.rst *.txt LICENSE\n"
  },
  {
    "path": "README.rst",
    "chars": 6900,
    "preview": "Itaú Scraper\n============\n\nScraper para baixar seus extratos do Itaú com um comando.\n\nMotivação\n---------\n\nAs APIs viera"
  },
  {
    "path": "itauscraper/__init__.py",
    "chars": 44,
    "preview": "from itauscraper.scraper import ItauScraper\n"
  },
  {
    "path": "itauscraper/__main__.py",
    "chars": 40,
    "preview": "from itauscraper import cli\n\ncli.main()\n"
  },
  {
    "path": "itauscraper/cli.py",
    "chars": 1834,
    "preview": "\"\"\"Command line interface.\"\"\"\nimport argparse\n\nfrom getpass import getpass\nfrom tabulate import tabulate\n\nfrom itauscrap"
  },
  {
    "path": "itauscraper/converter.py",
    "chars": 2401,
    "preview": "\"\"\"Funções de conversão usada pelo scraper do Itaú.\"\"\"\nimport datetime\nfrom dateutil.parser import parse\nfrom dateutil.r"
  },
  {
    "path": "itauscraper/itertools.py",
    "chars": 239,
    "preview": "\"\"\"Itertools recipies from Python documentation.\"\"\"\n\n\ndef grouper(iterable, size=2):\n    \"\"\"\n    Collect data into fixed"
  },
  {
    "path": "itauscraper/pages.py",
    "chars": 4558,
    "preview": "\"\"\"Classes que sabem extrair conteúdos das páginas do Itaú.\"\"\"\nfrom lxml import html\n\nfrom itauscraper.converter import "
  },
  {
    "path": "itauscraper/scraper.py",
    "chars": 2940,
    "preview": "\"\"\"Lógica do navegação no site do Itaú.\"\"\"\nimport requests\n\nfrom itauscraper.pages import CardMenuPage, StatementPage, M"
  },
  {
    "path": "requirements.txt",
    "chars": 68,
    "preview": "lxml==3.8.0\npython-dateutil==2.6.1\nrequests==2.18.1\ntabulate==0.7.7\n"
  },
  {
    "path": "setup.py",
    "chars": 1744,
    "preview": "# coding: utf-8\nfrom setuptools import setup\nimport os\n\n\nREADME = os.path.join(os.path.dirname(__file__), 'README.rst')\n"
  }
]

About this extraction

This page contains the full source code of the henriquebastos/itauscraper GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 13 files (28.9 KB), approximately 7.7k tokens, and a symbol index with 37 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!