到目前为止,我的代码是:
year = range(1958,2013)
randomYear = random.choice(year)
randomYear = str(randomYear)
page = range(1,5)
randomPage = random.choice(page)
randomPage = str(randomPage)
print(randomPage, randomYear)
url = 'http://www.billboard.com/artists/top-100/'+randomYear+'?page='+randomPage
url1 = urlopen(url)
htmlSource = url1.read()
url1.close()
soup = BeautifulSoup(htmlSource)
listm = soup.findAll('article', {'class': 'masonry-brick','style' : 'position; absolute; top; 0px; left: 0px;'})
for listm in soup.findAll('div',{'class': 'thumbnail'}):
for listm in soup.find('img alt')(''):
print(listm)
我要做的是获取img alt =“文本。我认为我有正确的提示,但没有显示任何内容。
要获取<img>
具有alt
属性的元素,可以使用soup('img', alt=True)
:
print("\n".join([img['alt'] for img in div.find_all('img', alt=True)]))
不要将相同的名称用于不同的用途,这会损害代码的可读性:
soup = BeautifulSoup(htmlSource)
articles = soup('article', 'masonry-brick',
style='position; absolute; top; 0px; left: 0px;')
for div in soup.find_all('div', 'thumbnail'):
for img in div.find_all('img', alt=True):
print(img['alt'])
注意:articles
未使用。
我只需要一个img标签。我怎样才能做到这一点?
您可以使用.find()
method获得每个<img>
元素<div>
:
for div in soup.find_all('div', 'thumbnail'):
img = div.find('img', alt=True)
print(img['alt'])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句