gpt4 book ai didi

python - 使用 beautifulsoup 显示来自 img alt 标签的文本

转载 作者:太空宇宙 更新时间:2023-11-03 13:45:57 24 4
gpt4 key购买 nike

到目前为止我的代码是:

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未使用。

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

你可以使用 .find()方法,得到一个<img>每个 <div> 的元素:

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

关于python - 使用 beautifulsoup 显示来自 img alt 标签的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20649048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com