python - 从 Banxico 的下拉框中消除通货膨胀

标签 python

我正在尝试从 Mexico's central 中提取下拉值给定月份和年份输入,我想避免使用 Selenium,因为我不想每次运行脚本时都打开 chrome 窗口。这是我到目前为止所尝试过的:

Twill

from twill.commands import *
go("http://www.banxico.org.mx/portal-inflacion/inflacion.html")
showforms()
Output: Form name=_BBM_MenuForm (#1)
## ## __Name__________________ __Type___ __ID________ 
__Value__________________
1     url                      hidden    url          
/AplBusquedasBM2/bgenwww_in.jsp 
2     appname                  hidden    appname      bmsearch 
3     _action                  hidden    _action      search 
4     _lang                    hidden    _lang        es 
5     _userquery               text      _userquery   Buscar... 
6     submit                   submit    (None)        
7     _P_BM_Deposito           select    _P_BM_De ... ['B', 'M', '_', 'W', 'W', 'W', ';',  ... 

我认为提交输入就是我正在寻找的内容,但我不知道如何输入月份和年份数据。

Mechanize

import mechanize
br = mechanize.Browser()

b = br.open("http://www.banxico.org.mx/portal-inflacion/inflacion.html")

b.select_form(nr=0)

form = br.form

print(form)

Output:
Traceback (most recent call last):
  File "pago_ext.py", line 16, in <module>
    b.select_form(nr=0)
  File "/usr/local/lib/python2.7/dist-packages/mechanize/_response.py", line 106, in __getattr__
    return getattr(wrapped, name)
AttributeError: closeable_response instance has no attribute 'select_form'

考虑到我对 HTML 不太了解,如何访问下拉菜单???

最佳答案

如果您仔细检查该页面(提示:查找在“网络”选项卡中发出的请求(在 Firefox 中为CTRL + Shift + E)),您会注意到每次更改下拉框的值(月/年)时,数据都会以 json 格式到达。 URL 始终相同,只是末尾的日期发生了变化。要知道,通过一些技巧,您可以轻松获取所有数据。

这是您的抓取工具:

import requests
from collections import OrderedDict

def get_annual_data(year):

    data = []

    for i in range(1, 13):
        url = 'http://www.banxico.org.mx/tipcamb/datosieajax?accion=dato&idSeries=SP30577,SP30578,SP30579,SP74660,SP74661,SP74662,SP74663,SP74664,SP74665&decimales=2,2,2,2,2,2,2,2,2&fecha=01/{0}/{1}'.format('0' + str(i) if i < 10 else i, str(year))
        x = requests.get(url).json()
        data.append(x)

    years_data = OrderedDict()

    for i, x in enumerate(data):

        month_data = OrderedDict()

        month_data['INPC índice general'] = {
            'Mensual': data[i]['body'][0]['mensaje'],
            'Acumulada en el año': data[i]['body'][2]['mensaje'],
            'Anual': data[i]['body'][1]['mensaje']
        }

        month_data['INPC subyacente'] = {
            'Mensual': data[i]['body'][3]['mensaje'],
            'Acumulada en el año': data[i]['body'][4]['mensaje'],
            'Anual': data[i]['body'][5]['mensaje']
        }

        month_data['INPC no subyacente'] = {
            'Mensual': data[i]['body'][6]['mensaje'],
            'Acumulada en el año': data[i]['body'][7]['mensaje'],
            'Anual': data[i]['body'][8]['mensaje']
        }

        years_data[i + 1] = month_data

    return years_data

def get_data(start_year, end_year):

    all_data = OrderedDict()

    for i in range(start_year, end_year + 1):
        all_data[i] = get_annual_data(i)

    return all_data

基本上,您可以使用 get_data(start_year, end_year) 运行抓取工具(例如 get_data(2010, 2016))。这些信息将位于一个很好的 OrderedDict 中,每年是一个键,与该年相对应的所有数据都是一个值。如果您想查看结构的样子,可以漂亮地打印它(from pprint import pprint; pprint(get_data(2010, 2016)))。例如,您可以访问这些值,如下所示:print(get_data(2014, 2016)[2014][1]['INPC índice general']),这将为您提供: {'月经':'0.89','Acumulada en el año':'0.89','年度':'4.48'}

关于python - 从 Banxico 的下拉框中消除通货膨胀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46415577/

相关文章:

python - 我如何知道我的列表是否全为 1?

相同unicode的python不同长度

python - 选择按钮时如何更改按钮颜色以及我只想使用pyqt4选择一个按钮的每个布局?

Python 3.3 似乎无法在 pocketsphinx 库中找到解码器模块

python - 无法登录我在 django 中创建的用户帐户

python - 如何将 Pandas 列的值设置为列表

python - 缩放图像不会产生明显的变化

Python:替换数组中的值

python - Pyodbc 访问同一台服务器上的多个数据库

python与 Pandas : file size (44546) not 512 + multiple of sector size (512)