7

我尝试解析 html 页面并获取货币值并写入 csv。我有以下代码:

#!/usr/bin/env python

import urllib2
from BeautifulSoup import BeautifulSoup

contenturl = "http://www.bank.gov.ua/control/en/curmetal/detail/currency?period=daily"
soup = BeautifulSoup(urllib2.urlopen(contenturl).read())

table = soup.find('div', attrs={'class': 'content'})

rows = table.findAll('tr')
for tr in rows:
    cols = tr.findAll('td')
    for td in cols:
        text = td.find(text=True) + ';'
        print text,
    print

问题是,我不知道如何仅检索货币值。我尝试了一些正则表达式,例如 '^[0-9]{3}' - 从 3 位数字开始,但它不起作用。

4

1 回答 1

9

您最好选择表格中的特定单元格。td具有该类的单元格cell_c包含您感兴趣的数据,最后一个始终是货币汇率:

rows = table.findAll('tr')
for tr in rows:
    cols = tr.findAll('td')
    if 'cell_c' in cols[0]['class']:
        # currency row
        digital_code, letter_code, units, name, rate = [c.text for c in cols]
        print digital_code, letter_code, units, name, rate

使用单独变量中的数据,您现在可以将文本转换为十进制数字,将它们存储在数据库中,等等。

于 2013-03-06T14:59:18.207 回答