到目前为止我的代码是:
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', ) for div in soup.find_all('div', 'thumbnail'): for img in div.find_all('img', alt=True): print(img['alt'])
注意:articles
未使用.
我只需要一个img标签.我怎样才能做到这一点?
你可以使用.find()
方法来获得一个<img>
元素<div>
:
for div in soup.find_all('div', 'thumbnail'): img = div.find('img', alt=True) print(img['alt'])