使用beautifulsoup从img alt标签显示文本

 後誨A沩鉨乄菰単 发布于 2023-02-09 15:44

到目前为止我的代码是:

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 =''文字.我认为我有一点正确,但它没有显示任何内容.

1 个回答
  • 要获取<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'])
    

    2023-02-09 15:47 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有