2013-03-06 63 views
7

我嘗試解析html頁面併爲貨幣提取值並寫入csv。 我有以下代碼:如何用python和beautifulsoup解析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位數開頭,但它不起作用。

+0

你使用BeautifulSoup 3而不是4的原因是什麼?不是說你的問題很重要,但是bs4在地方提供了更好的功能。 – 2013-03-06 14:52:57

+0

您是否想要獲得「官方匯率」欄目的值? – jurgenreza 2013-03-06 15:02:51

回答

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 

隨着獨立變量的數據,你現在可以將文本轉換爲十進制數,存儲他們在數據庫中,無論如何。