0

@martineauコードを更新しましたが、これはあなたが意図したものですか? NameError の代わりに KeyError を処理するにはどうすればよいですか?

url = "http://app2.nea.gov.sg/anti-pollution-radiation-protection/air-pollution/psi/psi-readings-over-the-last-24-hours"
web_soup = soup(urllib2.urlopen(url))

table = web_soup.find(name="div", attrs={'class': 'c1'}).find_all(name="div")[4].find_all('table')[0]

data = {}
cur_time = datetime.datetime.strptime("12AM", "%I%p")
for tr_index, tr in enumerate(table.find_all('tr')):
    if 'Time' in tr.text:
        continue
    for td_index, td in enumerate(tr.find_all('td')):
        if not td_index:
            continue
        data[cur_time] = td.text.strip()

        if td.find('strong'):
            bold_time = cur_time
            data[bold_time] = '20'
        cur_time += datetime.timedelta(hours=1)

        default_value = '20' # whatever you want it to be

    try:
        bold = data[bold_time]
    except NameError:

        bold_time = beforebold = beforebeforebold = default_value
    # might want to set "bold" to something, too, if needed
    else:   
        beforebold = data.get(bold_time - datetime.timedelta(hours=1)) 
        beforebeforebold =  data.get(bold_time - datetime.timedelta(hours=2))

これは、計算を行うためにデータを出力する場所です。

print bold
print beforebold
print beforebeforebold
4

2 に答える 2