get div attribute val und div text body
Hier ist ein kleiner Code, um den Wert div attr zu erhalten. Alle div-Namen sind mit demselben attr-Namen identisch.
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
First Print gibt einige URLs (manchmal 4, 6, 8 usw.) und dann
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'
wie alle Div-Namen gleich sind mit dem gleichensmturl
attr name, warum gibt esKeyError
irgendeine Hilfe