美丽汤“list object has no attribute”错误

5

我正在尝试使用以下代码从气象网站中抓取温度数据:

    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文档,但仍然很生疏,因此无法理解。请帮助这个新手!

2个回答

7
.findAll() 方法返回一个匹配结果的 列表。如果你只需要一个结果,使用 .find() 方法。或者,像代码中的其余部分一样挑选出特定的元素,或循环遍历结果:
location = soup.find('h1').text

或者

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

或者

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

1
这很简单。 findAll 返回列表,所以如果您确定只有一个感兴趣的元素,则应该使用 soup.findAll('H1')[0].text

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接