2013-03-10 73 views
3

我想用下面刮從weather site溫度:beautifulsoup「列表對象有沒有屬性」的錯誤

import urllib2 
from BeautifulSoup import BeautifulSoup 

f = open('airport_temp.tsv', 'w') 

f.write("Location" + "\t" + "High Temp (F)" + "\t" + "Low Temp (F)" + "\t" + "Mean Humidity" + "\n") 

eventually parse from http://www.wunderground.com/history/airport/\w{4}/2012/\d{2}/1/DailyHistory.html 

for x in range(10): 
    locationstamp = "Location " + str(x) 
    print "Getting data for " + locationstamp 
    url = 'http://www.wunderground.com/history/airport/KAPA/2013/3/1/DailyHistory.html' 

    page = urllib2.urlopen(url) 
    soup = BeautifulSoup(page) 

    location = soup.findAll('h1').text 
    locsent = location.split() 
    loc = str(locsent[3,6]) 

    hightemp = soup.findAll('nobr')[6].text 
    htemp = hightemp.split() 
    ht = str(htemp[1]) 

    lowtemp = soup.findAll('nobr')[10].text 
    ltemp = lowtemp.split() 
    lt = str(ltemp[1]) 

    avghum = soup.findAll('td')[23].text 

    f.write(loc + "\t|" + ht + "\t|" + lt + "\t|" + avghum + "\n") 

f.close() 

不幸的是,我得到一個錯誤說:

Getting data for Location 0 
Traceback (most recent call last): 
    File "airportweather.py", line 18, in <module> 
    location = soup.findAll('H1').text 
AttributeError: 'list' object has no attribute 'text' 

我通過BS和Python文檔查看,但我仍然很綠,所以我無法弄清楚。請幫助這個新手!

回答

1

這很簡單。 findAll返回列表,所以如果你確信只有一個有意思嗎元素,則:soup.findAll('H1')[0].text應該工作

6

.findAll()方法返回匹配的列表。如果您想要一個結果,請改用.find()方法。另外,挑選出一個特定的元素,如代碼執行,或循環的其餘部分在結果:

location = soup.find('h1').text 

locations = [el.text for el in soup.findAll('h1')] 

location = soup.findAll('h1')[2].text 
+0

完美的感謝你們倆的幫助! – Brad 2013-03-10 18:57:25

相關問題