[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# dotenv\n.env\n\n# virtualenv\n.venv\nvenv/\nENV/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n\n.idea/\n.DS_Store\n"
  },
  {
    "path": "LICENSE",
    "content": "                   GNU LESSER GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n\n  This version of the GNU Lesser General Public License incorporates\nthe terms and conditions of version 3 of the GNU General Public\nLicense, supplemented by the additional permissions listed below.\n\n  0. Additional Definitions.\n\n  As used herein, \"this License\" refers to version 3 of the GNU Lesser\nGeneral Public License, and the \"GNU GPL\" refers to version 3 of the GNU\nGeneral Public License.\n\n  \"The Library\" refers to a covered work governed by this License,\nother than an Application or a Combined Work as defined below.\n\n  An \"Application\" is any work that makes use of an interface provided\nby the Library, but which is not otherwise based on the Library.\nDefining a subclass of a class defined by the Library is deemed a mode\nof using an interface provided by the Library.\n\n  A \"Combined Work\" is a work produced by combining or linking an\nApplication with the Library.  The particular version of the Library\nwith which the Combined Work was made is also called the \"Linked\nVersion\".\n\n  The \"Minimal Corresponding Source\" for a Combined Work means the\nCorresponding Source for the Combined Work, excluding any source code\nfor portions of the Combined Work that, considered in isolation, are\nbased on the Application, and not on the Linked Version.\n\n  The \"Corresponding Application Code\" for a Combined Work means the\nobject code and/or source code for the Application, including any data\nand utility programs needed for reproducing the Combined Work from the\nApplication, but excluding the System Libraries of the Combined Work.\n\n  1. Exception to Section 3 of the GNU GPL.\n\n  You may convey a covered work under sections 3 and 4 of this License\nwithout being bound by section 3 of the GNU GPL.\n\n  2. Conveying Modified Versions.\n\n  If you modify a copy of the Library, and, in your modifications, a\nfacility refers to a function or data to be supplied by an Application\nthat uses the facility (other than as an argument passed when the\nfacility is invoked), then you may convey a copy of the modified\nversion:\n\n   a) under this License, provided that you make a good faith effort to\n   ensure that, in the event an Application does not supply the\n   function or data, the facility still operates, and performs\n   whatever part of its purpose remains meaningful, or\n\n   b) under the GNU GPL, with none of the additional permissions of\n   this License applicable to that copy.\n\n  3. Object Code Incorporating Material from Library Header Files.\n\n  The object code form of an Application may incorporate material from\na header file that is part of the Library.  You may convey such object\ncode under terms of your choice, provided that, if the incorporated\nmaterial is not limited to numerical parameters, data structure\nlayouts and accessors, or small macros, inline functions and templates\n(ten or fewer lines in length), you do both of the following:\n\n   a) Give prominent notice with each copy of the object code that the\n   Library is used in it and that the Library and its use are\n   covered by this License.\n\n   b) Accompany the object code with a copy of the GNU GPL and this license\n   document.\n\n  4. Combined Works.\n\n  You may convey a Combined Work under terms of your choice that,\ntaken together, effectively do not restrict modification of the\nportions of the Library contained in the Combined Work and reverse\nengineering for debugging such modifications, if you also do each of\nthe following:\n\n   a) Give prominent notice with each copy of the Combined Work that\n   the Library is used in it and that the Library and its use are\n   covered by this License.\n\n   b) Accompany the Combined Work with a copy of the GNU GPL and this license\n   document.\n\n   c) For a Combined Work that displays copyright notices during\n   execution, include the copyright notice for the Library among\n   these notices, as well as a reference directing the user to the\n   copies of the GNU GPL and this license document.\n\n   d) Do one of the following:\n\n       0) Convey the Minimal Corresponding Source under the terms of this\n       License, and the Corresponding Application Code in a form\n       suitable for, and under terms that permit, the user to\n       recombine or relink the Application with a modified version of\n       the Linked Version to produce a modified Combined Work, in the\n       manner specified by section 6 of the GNU GPL for conveying\n       Corresponding Source.\n\n       1) Use a suitable shared library mechanism for linking with the\n       Library.  A suitable mechanism is one that (a) uses at run time\n       a copy of the Library already present on the user's computer\n       system, and (b) will operate properly with a modified version\n       of the Library that is interface-compatible with the Linked\n       Version.\n\n   e) Provide Installation Information, but only if you would otherwise\n   be required to provide such information under section 6 of the\n   GNU GPL, and only to the extent that such information is\n   necessary to install and execute a modified version of the\n   Combined Work produced by recombining or relinking the\n   Application with a modified version of the Linked Version. (If\n   you use option 4d0, the Installation Information must accompany\n   the Minimal Corresponding Source and Corresponding Application\n   Code. If you use option 4d1, you must provide the Installation\n   Information in the manner specified by section 6 of the GNU GPL\n   for conveying Corresponding Source.)\n\n  5. Combined Libraries.\n\n  You may place library facilities that are a work based on the\nLibrary side by side in a single library together with other library\nfacilities that are not Applications and are not covered by this\nLicense, and convey such a combined library under terms of your\nchoice, if you do both of the following:\n\n   a) Accompany the combined library with a copy of the same work based\n   on the Library, uncombined with any other library facilities,\n   conveyed under the terms of this License.\n\n   b) Give prominent notice with the combined library that part of it\n   is a work based on the Library, and explaining where to find the\n   accompanying uncombined form of the same work.\n\n  6. Revised Versions of the GNU Lesser General Public License.\n\n  The Free Software Foundation may publish revised and/or new versions\nof the GNU Lesser General Public License from time to time. Such new\nversions will be similar in spirit to the present version, but may\ndiffer in detail to address new problems or concerns.\n\n  Each version is given a distinguishing version number. If the\nLibrary as you received it specifies that a certain numbered version\nof the GNU Lesser General Public License \"or any later version\"\napplies to it, you have the option of following the terms and\nconditions either of that published version or of any later version\npublished by the Free Software Foundation. If the Library as you\nreceived it does not specify a version number of the GNU Lesser\nGeneral Public License, you may choose any version of the GNU Lesser\nGeneral Public License ever published by the Free Software Foundation.\n\n  If the Library as you received it specifies that a proxy can decide\nwhether future versions of the GNU Lesser General Public License shall\napply, that proxy's public statement of acceptance of any version is\npermanent authorization for you to choose that version for the\nLibrary.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include *.rst *.txt LICENSE\n"
  },
  {
    "path": "README.rst",
    "content": "Itaú Scraper\n============\n\nScraper para baixar seus extratos do Itaú com um comando.\n\nMotivação\n---------\n\nAs APIs vieram para ficar, mas a maioria dos bancos ainda não oferecem forma\nfácil para seus clientes extraírem seus próprios dados. Algo tão simples\nquanto obter o seu extrato bancário é um sofrimento para sistematizar.\n\nPesquisei se existia algo pronto para o Itaú e encontrei o\n`bankscraper <https://github.com/kamushadenes/bankscraper>`_ do\n`Kamus <http://endurance.hyadesinc.com/>`_ que disponibiliza vários scripts\ninteressantes. Infelizmente o do Itaú não estava mais funcionando,\nmas estudando seu código encontrei uma boa dica:\n\n    O site do Itaú para computador é todo complicado para navegar com muita\n    mágica em javascript. Mas e o site para disponsitivos móveis?\n\nAtivei o `\"mobile mode\" <https://developers.google.com/web/tools/chrome-devtools/device-mode/>`_\ndo Chrome com o `Postman <https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop>`_\ne o `Postman Interceptor <https://chrome.google.com/webstore/detail/postman-interceptor/aicmkgpgakddgnaphhhpliifpcfhicfo>`_\npara rastrear todas as requisições e **bingo**. De fato é bem mais simples.\n\nDecidi escrever este artigo para explicar o procedimento, evidenciar as\nbizarrices e quem sabe facilitar a manutenção futura quando algo mudar.\n\nEste script funciona apenas para contas *Pessoa Física*, pois o Itaú força\nempresas a usarem seu aplicativo no celular não dando acesso ao site móvel\npelo navegador.\n\nComo funciona\n~~~~~~~~~~~~~\n\nO código é simples e usa `Python 3 <https://www.python.org/>`_ com a biblioteca\n`requests <http://docs.python-requests.org/en/master/>`_ para a navegação\ne `lxml <http://lxml.de/>`_ para a extração de dados com\n`xpath <http://ricostacruz.com/cheatsheets/xpath.html>`_.\n\nMais do que explicar o código em si, o importante é entender o fluxo de\nnavegação que ele precisa reproduzir.\n\nO protocolo HTTP é *assíncrono* exigindo que cada requisição envie novamente\ntodas as informações necessárias. No entanto, o site do banco cria uma dinâmica\ncliente-servidor estabelecendo dependência entre as requisições mudando inclusive\nas urls de navegação. Por isso todo o processo acontece sequencialmente, cheio de\netapas intermediárias que não seriam necessárias em condições normais.\n\nUsando o ``requests.Session`` conseguimos reproduzir o efeito de navegação contínua\nentre várias páginas propagando *cookies* e outros *cabeçalhos*.\n\nA classe ``MobileSession`` implementa os cabeçalhos para nos fazermos\npassar por um browser de celular.\n\nA classe ``ItauScraper`` usa a ``session`` para realizar o ``login`` e\nconsultar o ``extrato``.\n\nO login\n~~~~~~~\n\nPara fazer o ``login`` no site do banco é preciso acessar uma url inicial para\ndescobrirmos a url de login real, que muda de tempos em tempos pelo que eu entendi.\n\nCom a *url de login* correta, agora é preciso fazer um novo ``GET`` para obter\ninformações que o ASP.NET injeta no formulário de login e então realizar o POST\nefetuando a autenticação.\n\nDepois do login feito, somos redirecionados para uma página com um menu de\nnavegação. Esta página não é usada no fluxo, mas quando quisermos implementar novas\nfuncionalidades no ``ItauScraper`` é nela que deveremos começar.\n\n.. image:: https://raw.githubusercontent.com/henriquebastos/itauscraper/master/docs/itau-login.jpg\n\nO extrato\n~~~~~~~~~\n\nQuando acessamos a *url do extrato*, por padrão é exibido o extrato dos *últimos 3 dias*.\nNo fim da página do extrato tem 4 links para listar os extratos dos períodos\n7, 15, 30 e 90 dias. Estas urls parecem mudar de tempos em tempos, como a do login,\nentão é preciso *extrair o link* para *90 dias* e obter o extrato com outro ``GET``.\n\n.. image:: https://raw.githubusercontent.com/henriquebastos/itauscraper/master/docs/itau-extrato.jpg\n\nCom o extrato do maior período:\n\n1. Extraímos a informação do html;\n2. Reconstruímos a tabela com as colunas: data, descrição e valor;\n3. Filtramos as linhas de saldo que não correspondem a um lançamento;\n4. Convertemos cada *data* para o tipo ``datetime.date``;\n5. Convertemos cada *valor* para o tipo ``Decimal``;\n\nNo final, temos uma *tupla de tuplas* na forma:\n\n.. code-block:: python\n\n    ((datetime.date(2017, 1, 1), 'RSHOP-LOJA1', Decimal('-1.99')),\n     (datetime.date(2017, 1, 2), 'RSHOP-LOJA2', Decimal('-5.00')),\n     (datetime.date(2017, 1, 3), 'TBI 1234567', Decimal('10.00')))\n\nO cartão\n~~~~~~~~\n\nQuando acessamos a *url do cartão*, são exibidas 3 opções para listar:\n\n1. a fatura anterior;\n2. a fatura atual;\n3. os lançamentos parciais da próxima fatura.\n\nEstas urls parecem mudar de tempos em tempos, então é preciso *extrair o link* para a *fatura atual*\ne realizar um novo ``GET`` para obter o extrato de lançamentos.\n\n.. image:: https://raw.githubusercontent.com/henriquebastos/itauscraper/master/docs/itau-cartao.jpg\n\nAlém dos lançamentos, há na página um resumo com totais.\n\nCom o extrato do cartão:\n\n1. Extraímos a informação do html;\n2. Reconstruímos o resumo como um *dicionário*.\n3. Reconstruímos a tabela com as colunas: data, descrição e valor;\n4. Convertemos cada *data* para o tipo ``datetime.date``;\n5. Convertemos cada *valor* para o tipo ``Decimal``;\n\nNo final, temos um *dicionário* com o sumário da fatura e uma *tupla de tuplas* na forma:\n\n.. code-block:: python\n\n    # sumário\n    {'Total dos lançamentos anteriores': Decimal('4.99'),\n     'Créditos e pgtos': Decimal('4.99'),\n     'Total nacional': Decimal('1.99'),\n     'Total internacional': Decimal('0.00'),\n     'Dólar em 06/07/2017': Decimal('9.99'),\n     'Total dos lançamentos atuais': Decimal('1.99'),\n     'Pagamento mínimo': Decimal('0.25')}\n\n    # lançamentos\n    ((datetime.date(2017, 1, 1), 'RSHOP-LOJA1', Decimal('-1.99')),\n     (datetime.date(2017, 1, 2), 'RSHOP-LOJA2', Decimal('-5.00')),\n     (datetime.date(2017, 1, 3), 'TBI 1234567', Decimal('10.00')))\n\nComo usar\n---------\n\nUse pela linha de comando:\n\n.. code-block:: console\n\n $ itauscraper --extrato --cartao --agencia 1234 --conta 12345 --digito 6\n Digite sua senha do Internet Banking: \n\n\nOu:\n\n.. code-block:: console\n\n $ itauscraper --extrato --cartao --agencia 1234 --conta 12345 --digito 6 --senha SECRET\n\n\nOu importe direto no seu código:\n\n.. code-block:: python\n\n from itauscraper import ItauScraper\n\n itau = ItauScraper(agencia='1234', conta='12345', digito='6', senha='SECRET')\n itau.login():\n print(itau.extrato())\n print(itau.cartao())\n # TODO: Divirta-se!\n\nPara conhecer todas as opções execute:\n\n.. code-block:: console\n\n $ itauscraper -h\n\n\nDevelopment\n-----------\n\n.. code-block:: console\n\n git clone https://github.com/henriquebastos/itauscraper.git\n cd itauscraper\n python -m venv -p python3.6 .venv\n source .venv/bin/activate\n pip install -r requirements.txt\n\n\nLicença\n-------\n\nCopyright (C) 2017 Henrique Bastos.\n\nEste código é distribuído nos termos da \"GNU LGPLv3\". Veja o arquivo LICENSE para detalhes.\n"
  },
  {
    "path": "itauscraper/__init__.py",
    "content": "from itauscraper.scraper import ItauScraper\n"
  },
  {
    "path": "itauscraper/__main__.py",
    "content": "from itauscraper import cli\n\ncli.main()\n"
  },
  {
    "path": "itauscraper/cli.py",
    "content": "\"\"\"Command line interface.\"\"\"\nimport argparse\n\nfrom getpass import getpass\nfrom tabulate import tabulate\n\nfrom itauscraper.scraper import ItauScraper\n\n\ndef csv(data):\n    lines = (','.join((str(col) for col in row)) for row in data)\n    return '\\n'.join(lines)\n\n\ndef table(data):\n    return tabulate(data, floatfmt='.2f')\n\n\ndef main():\n    parser = argparse.ArgumentParser(prog='itau',\n                                     description='Scraper para baixar seus extratos do Itaú com um comando.')\n\n    parser.add_argument('--extrato', action='store_true', help='Lista extrato da conta corrente.')\n    parser.add_argument('--cartao', action='store_true', help='Lista extrato do cartão de crédito.')\n    parser.add_argument('--agencia', '-a', help='Agência na forma 0000', required=True)\n    parser.add_argument('--conta', '-c', help='Conta sem dígito na forma 00000', required=True)\n    parser.add_argument('--digito', '-d', help='Dígito da conta na forma 0', required=True)\n    parser.add_argument('--senha', '-s', help='Senha eletrônica da conta no Itaú.')\n    parser.add_argument('--csv', help='Imprime os dados em CSV.', dest='output',\n                        action='store_const', const=csv, default=table)\n\n    args = parser.parse_args()\n\n    if not (args.extrato or args.cartao):\n        parser.exit(0, \"Indique a operação: --extrato e/ou --cartao\\n\")\n\n    output = args.output  # csv or table (default)\n    senha = args.senha or getpass(\"Digite sua senha do Internet Banking: \")\n\n    itau = ItauScraper(args.agencia, args.conta, args.digito, senha)\n\n    assert itau.login()\n\n    if args.extrato:\n        data = itau.extrato()\n        print()\n        print(output(data))\n\n    if args.cartao:\n        summary, data = itau.cartao()\n        print()\n        print(output(summary.items()))\n        print()\n        print(output(data))\n"
  },
  {
    "path": "itauscraper/converter.py",
    "content": "\"\"\"Funções de conversão usada pelo scraper do Itaú.\"\"\"\nimport datetime\nfrom dateutil.parser import parse\nfrom dateutil.relativedelta import relativedelta\nfrom decimal import Decimal\n\n\ndef date(s):\n    \"\"\"Converte strings 'DD/MM' em datetime.date.\n    Leva em consideração ano anterior para meses maiores que o mês corrente.\n    \"\"\"\n    dt = parse(s, dayfirst=True)\n\n    # Se o mês do lançamento > mês atual, o lançamento é do ano passado.\n    if dt.month > datetime.date.today().month:\n        dt += relativedelta(years=-1)\n\n    dt = dt.date()\n\n    return dt\n\n\ndef decimal(s):\n    \"\"\"Converte strings para Decimal('-9876.54').\n    >>> assert decimal('9.876,54-') == Decimal('-9876.54')\n    >>> assert decimal('9.876,54 D') == Decimal('-9876.54')\n    >>> assert decimal('9.876,54 C') == Decimal('9876.54')\n    >>> assert decimal('R$ 9.876,54') == Decimal('9876.54')\n    >>> assert decimal('R$ -9.876,54') == Decimal('-9876.54')\n    \"\"\"\n    s = s.replace('.', '')\n    s = s.replace(',', '.')\n\n    if s.startswith('R$ '):\n        s = s[3:]\n\n    if s.endswith('-'):\n        s = s[-1] + s[:-1]\n    elif s.endswith(' D'):\n        s = '-' + s[:-2]\n    elif s.endswith(' C'):\n        s = s[:-2]\n\n    return Decimal(s)\n\n\ndef is_balance(s):\n    \"\"\"Retorna True quando s é uma entrada de saldo em vez de lançamento.\"\"\"\n    return s in ('S A L D O',\n                 '(-) SALDO A LIBERAR',\n                 'SALDO FINAL DISPONIVEL',\n                 'SALDO ANTERIOR')\n\n\ndef statements(iterable):\n    \"\"\"Converte dados do extrato de texto para tipos Python.\n    Linhas de saldo são ignoradas.\n    Entrada: (('21/07', 'Lançamento', '9.876,54-'), ...)\n    Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...)\n    \"\"\"\n    return ((date(a), b, decimal(c)) for a, b, c in iterable if not is_balance(b))\n\n\ndef card_statements(iterable):\n    \"\"\"Converte dados do extrato do cartão de texto para tipos Python.\n    Entrada: (('21/07', 'Lançamento', '9.876,54 D'), ...)\n    Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...)\n    \"\"\"\n    return ((date(a), b, decimal(c)) for a, b, c in iterable)\n\n\ndef card_summary(iterable):\n    \"\"\"Converte dados do resumo do cartão de texto para tipos Python.\n    Entrada: (('Item do Resumo', 'R$ -9.876,54'), ...)\n    Saída..: (('Item do Resumo', Decimal('-9876.54')), ...)\n    \"\"\"\n    return ((a, decimal(b)) for a, b in iterable)\n"
  },
  {
    "path": "itauscraper/itertools.py",
    "content": "\"\"\"Itertools recipies from Python documentation.\"\"\"\n\n\ndef grouper(iterable, size=2):\n    \"\"\"\n    Collect data into fixed-length chunks or blocks.\n    grouper('ABCDEFGHI', 3) --> ABC DEF GHI\n    \"\"\"\n    return zip(*[iter(iterable)] * size)\n"
  },
  {
    "path": "itauscraper/pages.py",
    "content": "\"\"\"Classes que sabem extrair conteúdos das páginas do Itaú.\"\"\"\nfrom lxml import html\n\nfrom itauscraper.converter import card_statements, card_summary, statements\nfrom itauscraper.itertools import grouper\n\n\nclass Page:\n    \"\"\"Classe base usada para extrair informações relevantes do Itaú.\"\"\"\n\n    def __init__(self, response):\n        self.response = response\n        self.tree = html.fromstring(response.content)\n\n    def is_authenticated(self):\n        return b\"autenticado = 'S'\" in self.response.content\n\n\nclass FirstPage(Page):\n    \"\"\"Página inicial de onde extrairemos a url de login válida.\"\"\"\n\n    def valid_login_url(self):\n        # Extrai do html o parâmetro de sessão e anexa à url de login.\n        url = 'https://ww70.itau.com.br/M/LoginPF.aspx'\n\n        nl = self.tree.xpath(\"//a[starts-with(@href, '../Login')]/@href\")\n        href = nl[-1]\n        param = href.split('?')[-1]\n        url = ''.join((url, '?', param))\n        return url\n\n\nclass LoginPage(Page):\n    \"\"\"Página de login de onde extraímos o formulário de autenticação.\"\"\"\n\n    def formdata(self, agencia, conta, digito, senha):\n        # Extrai os nomes e valores dos campos do ASP.NET montando um dicionário.\n        xpath = \"//input[starts-with(@name, '__') and @value]/@*[name()='name' or name()='value']\"\n        viewstate = dict(grouper(self.tree.xpath(xpath)))\n\n        # Prepara o dicionário com dados do post combinado os dados do ASP.NET e os dados da conta.\n        data = {}\n        data.update(viewstate)\n        data.update({\n            'ctl00$ContentPlaceHolder1$txtAgenciaT': agencia,\n            'ctl00$ContentPlaceHolder1$txtContaT': conta,\n            'ctl00$ContentPlaceHolder1$txtDACT': digito,\n            'ctl00$ContentPlaceHolder1$txtPassT': senha,\n            'ctl00$ContentPlaceHolder1$btnLogInT.x': '12',\n            'ctl00$ContentPlaceHolder1$btnLogInT.y': '14',\n            'ctl00$hddAppTokenApp': '',\n            'ctl00$hddExisteApp': '',\n        })\n\n        return data\n\n\nclass MenuPage(Page):\n    \"\"\"Página com o menu de navegação do site do Itaú de onde extraímos as urls válidas.\"\"\"\n\n    def url_cartao(self):\n        # Extrai do html a url das faturas do cartão.\n        nl = self.tree.xpath(\"//span[.='CartÃµes']/ancestor::div[1]/a/@href\")\n        url = nl[-1]\n        return url\n\n\nclass StatementPage(Page):\n    def url_max_period(self):\n        # Extrai do html o parâmetro da url para a listagem dos últimos 90 dias e anexa à url do extrato.\n        url = 'https://ww70.itau.com.br/M/SaldoExtratoLancamentos.aspx'\n        nl = self.tree.xpath(\"//a[starts-with(@href, 'Saldo')]/@href\")\n        href = nl[-1]\n        param = href.split('?')[-1]\n        url = ''.join((url, '?', param))\n        return url\n\n    def statements(self):\n        # Extrai do html os lançamentos e transforma em\n        xpath = \"//fieldset[@id='ctl00_ContentPlaceHolder1_FieldExtratoTouch']//td[string-length(text())>1]/text()\"\n        nl = self.tree.xpath(xpath)\n        data = tuple(grouper(nl, size=3))  # Reconstroi a tabela de 3 em 3.\n        rows = data[1:]  # Ignora o cabeçalho da tabela.\n        stmts = tuple(statements(rows))  # Converte textos para tipos Python\n        return stmts\n\n\nclass CardMenuPage(Page):\n    BASE_URL = 'https://ww70.itau.com.br/M/FaturaCartaoCreditoQT.aspx'\n\n    def _url_menu(self, text):\n        nl = self.tree.xpath(\"//div[.='LanÃ§amentos {}']/ancestor::div[1]/a/@href\".format(text))\n        href = nl[-1]\n        param = href.split('?')[-1]\n        url = ''.join((self.BASE_URL, '?', param))\n        return url\n\n    def url_menu_current(self):\n        return self._url_menu('atuais')\n\n    def url_menu_previous(self):\n        return self._url_menu('anteriores')\n\n    def url_menu_next(self):\n        return self._url_menu('futuros')\n\n\nclass CardStatement(Page):\n    def summary(self):\n        xpath = \"//table[@id='ctl00_ContentPlaceHolder1_tbResumoTableT']//td/text()\"\n        nl = self.tree.xpath(xpath)\n        rows = tuple(grouper(nl, size=2))  # Reconstroi a tabela de 2 em 2.\n        return dict(card_summary(rows))  # Converte textos para tipos Python\n\n    def statements(self):\n        # Extrai do html os lançamentos do cartão.\n        xpath = \"//table[@id='ctl00_ContentPlaceHolder1_tbmovnacionalT']//*[@class='saldo']//td/text()\"\n        nl = self.tree.xpath(xpath)\n        data = tuple(grouper(nl, size=3))  # Reconstroi a tabela de 3 em 3.\n        rows = data[1:]  # Ignora o lançamento de pagamento anterior.\n        stmts = tuple(card_statements(rows))  # Converte textos para tipos Python\n        return stmts\n"
  },
  {
    "path": "itauscraper/scraper.py",
    "content": "\"\"\"Lógica do navegação no site do Itaú.\"\"\"\nimport requests\n\nfrom itauscraper.pages import CardMenuPage, StatementPage, MenuPage, LoginPage, FirstPage, CardStatement\n\n\nclass MobileSession(requests.Session):\n    \"\"\"Session customizado para se passar por navegador de dispositivo móvel.\"\"\"\n\n    def __init__(self):\n        super().__init__()\n\n        self.headers.update({\n            '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',\n            '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',\n            'Accept-Encoding': 'gzip, deflate, br',\n            'Accept-Language': 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4',\n        })\n\n\nclass ItauScraper:\n    \"\"\"Scraper do Itaú Pessoa Física.\"\"\"\n\n    def __init__(self, agencia, conta, digito, senha):\n        self.agencia = agencia\n        self.conta = conta\n        self.digito = digito\n        self.senha = senha\n\n        self.session = MobileSession()\n\n    def login(self):\n        url = 'https://ww70.itau.com.br/M/LoginPF.aspx'\n\n        # Faz um GET na url inválida de login para descobrir o parâmetro de sessão.\n        response = self.session.get(url)\n        page = FirstPage(response)\n\n        url = page.valid_login_url()\n\n        # Faz um GET na url válida de login para exibir o formulário com campos do ASP.NET.\n        response = self.session.get(url)\n        page = LoginPage(response)\n\n        # Faz o POST realizando o login.\n        data = page.formdata(self.agencia, self.conta, self.digito, self.senha)\n        response = self.session.post(url, data=data)\n        page = MenuPage(response)\n\n        return page\n\n    def extrato(self):\n        url = 'https://ww70.itau.com.br/M/SaldoExtratoLancamentos.aspx'\n\n        # Assumindo que estamos logados, faz um GET na url que lista os lançamentos.\n        # Por padrão serão mostrados lançamentos realizados nos últimos 3 dias.\n        response = self.session.get(url)\n        page = StatementPage(response)\n\n        url = page.url_max_period()\n\n        # Faz um GET para listar os lançamentos dos últimos 90 dias, que é o maior período possível.\n        response = self.session.get(url)\n        page = StatementPage(response)\n\n        stmts = page.statements()\n\n        return stmts\n\n    def cartao(self):\n        url = 'https://ww70.itau.com.br/M/FaturaCartaoCreditoQT.aspx'\n\n        # Assumindo que estamos logados, faz um GET na url que lista o menu do cartão.\n        response = self.session.get(url)\n        page = CardMenuPage(response)\n\n        # Faz um GET para listar os lançåmentos atuais do cartão.\n        url = page.url_menu_current()\n        response = self.session.get(url)\n        page = CardStatement(response)\n\n        summary = page.summary()\n        stmts = page.statements()\n\n        return summary, stmts\n\n"
  },
  {
    "path": "requirements.txt",
    "content": "lxml==3.8.0\npython-dateutil==2.6.1\nrequests==2.18.1\ntabulate==0.7.7\n"
  },
  {
    "path": "setup.py",
    "content": "# coding: utf-8\nfrom setuptools import setup\nimport os\n\n\nREADME = os.path.join(os.path.dirname(__file__), 'README.rst')\nREQUIREMENTS = os.path.join(os.path.dirname(__file__), 'requirements.txt')\n\n\nif __name__ == \"__main__\":\n    setup(name='itauscraper',\n          description='Scraper para baixar seus extratos do Itaú com um comando.',\n          version='1.0',\n          long_description=open(README).read(),\n          author=\"Henrique Bastos\", author_email=\"henrique@bastos.net\",\n          license=\"GNU LGPLv3\",\n          url='http://github.com/henriquebastos/itauscraper/',\n          keywords=['scraper', 'requests', 'lxml', 'itau', 'bank', 'finance', 'accounting'],\n          install_requires=open(REQUIREMENTS).readlines(),\n          packages=['itauscraper'],\n          package_dir={\"itauscraper\": \"itauscraper\"},\n          entry_points={\n              'console_scripts': [\n                  'itauscraper = itauscraper.cli:main',\n              ]\n          },\n          zip_safe=False,\n          platforms='any',\n          include_package_data=True,\n          classifiers=[\n              'Development Status :: 5 - Production/Stable',\n              'Environment :: Console',\n              'Intended Audience :: Financial and Insurance Industry',\n              'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',\n              'Natural Language :: Portuguese (Brazilian)',\n              'Programming Language :: Python :: 3.4',\n              'Programming Language :: Python :: 3.5',\n              'Programming Language :: Python :: 3.6',\n              'Programming Language :: Python :: 3 :: Only',\n              'Topic :: Office/Business :: Financial :: Accounting',\n              'Topic :: Utilities',\n          ])\n"
  }
]