obter o atributo div val e o corpo do texto div
Aqui está um código pequeno para obter o valor de atributo div. Todos os nomes div são iguais com o mesmo nome attr.
redditFile = urllib2.urlopen("http://www.bing.com/videos?q=owl")
redditHtml = redditFile.read()
redditFile.close()
soup = BeautifulSoup(redditHtml)
productDivs = soup.findAll('div', attrs={'class' : 'dg_u'})
for div in productDivs:
print div.find('div', {"class":"vthumb"})['smturl']
#print div.find("div", {"class":"tl text-body"}) This print none rather then div text
primeira impressão fornece alguns URLs (algumas vezes 4,6,8 etc) e depois
KeyError Traceback (most recent call last)
<ipython-input-34-cc950a8a84f7> in <module>()
26 productDivs = soup.findAll('div', attrs={'class' : 'dg_u'})
27 for div in productDivs:
---> 28 print div.find('div', {"class":"vthumb"})['smturl']
29 print div.find("div", {"class":"tl text-body"})
/usr/local/lib/python2.7/dist-packages/bs4/element.pyc in __getitem__(self, key)
903 """tag[key] returns the value of the 'key' attribute for the tag,
904 and throws an exception if it's not there."""
--> 905 return self.attrs[key]
906
907 def __iter__(self):
KeyError: 'smturl'
como todos os nomes div são iguais com os mesmossmturl
attr name, por que dáKeyError
qualquer ajuda?