beautifulsoup]清单对象没有属性"错误 [英] beautifulsoup "list object has no attribute" error
本文介绍了beautifulsoup]清单对象没有属性"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从天气气温刮网站使用下列内容:
I'm trying to scrape temperatures from a weather site using the following:
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()
不幸的是,我得到一个错误说:
Unfortunately, I get an error saying:
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的文件看,但我依然pretty绿色,所以我不能弄明白。请帮助这个新手!
I've looked through BS and Python documentation, but am still pretty green, so I couldn't figure it out. Please help this newbie!
推荐答案
的 .findAll()
方法返回一个匹配的列表的。如果你想的有一个的结果,使用 .find()
方法来代替。另外,挑选出一个特定的元素,如code做的其余部分,或者遍历结果:
The .findAll()
method returns a list of matches. If you wanted one result, use the .find()
method instead. Alternatively, pick out a specific element like the rest of the code does, or loop over the results:
location = soup.find('h1').text
或
locations = [el.text for el in soup.findAll('h1')]
或
location = soup.findAll('h1')[2].text
这篇关于beautifulsoup]清单对象没有属性&QUOT;错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文