用beautifulsoup显示img alt tag中的文本

2024-05-17 12:40:11 发布

您现在位置:Python中文网/ 问答频道 /正文

到目前为止,我的代码是:

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=''文本。我想我是对的,但它什么也没显示。


Tags: urltoppagerangerandomyearprintsoup
2条回答

我想你的意思是:

soup.find('img', alt='')

这将找到一个img标记,其属性alt的值为''(无)

要获取具有alt属性的<img>元素,可以使用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未使用。

I only need one img tag. How can I do this?

可以使用.find()方法,为每个<div>获取一个<img>元素:

for div in soup.find_all('div', 'thumbnail'):
    img = div.find('img', alt=True)
    print(img['alt'])

相关问题 更多 >