Web Scrap,Python和BeautifulSoup,如何存储输出

时间:2014-05-26 09:20:37

标签: python web-scraping

我正在尝试使用webscrap方法为www.wunderground.com获取一些温度和降水数据(他们有一个API,但我必须在我的项目中使用web scrap方法)

我的问题是我无法弄清楚如何在废品后存储我的数据。

我的代码有例如:

import urllib2  
from bs4 import BeautifulSoup
url = "http://www.wunderground.com/history/airport/KBUF/2014/5/25/DailyHistory.html"
soup = BeautifulSoup(urllib2.urlopen(url).read()

#Mean Temperature Values
mean_temp_row = soup.findAll('table')[0].findAll('tr')[2]
for tds in mean_temp_row.findAll('td'):
    print tds.text

我得到的输出是:

Mean Temperature

15 °C


16 °C

我想知道如何得到类似的内容:station = {"Temp_Mean":[15 , 16]}

2 个答案:

答案 0 :(得分:0)

此输出格式是否始终相同? 如果是,那么我们可以看到信息名称在行的第一个td上。然后,有一个空的td,然后是min,然后是空的,空的,最后是最大的

所以你可以这样做:

def celcius2float(celcius):
    return float(celcius.split('°')[0].strip())

cells = Mean_Temp_Row.findAll('td')
name = cells[0].text
min_temp = celcius2float(cells[2].text)
max_temp = celcius2float(cells[5].text)

# Then you can do all you want with this suff :
station = {name: [min_temp, max_temp]}

答案 1 :(得分:0)

在考虑了TurpIF的答案后,这是我的代码

def collect_data(url):
    soup = BeautifulSoup(urllib2.urlopen(url).read())
    Mean_temp = soup.findAll('table')[0].findAll('tr')[2].findAll('td')
    temp = Mean_temp[1].text.split()[0].encode('utf8')
    rows = soup.findAll('table')[0].findAll('tr')
    for num,row in enumerate(rows):
        if "Precipitation" in row.text:
            preci_line = num
    Preci = soup.findAll('table')[0].findAll('tr')[preci_line].findAll('td')  
    perci = Preci[1].text.split()[0].encode('utf8')
    return temp,perci

所以,

url = "http://www.wunderground.com/history/airport/KBUF/2014/5/25/DailyHistory.html"
temp,perci = collect_data(url)