【问题标题】:Display text from img alt tag with beautifulsoup使用 beautifulsoup 显示来自 img alt 标签的文本
【发布时间】:2013-12-18 03:14:43
【问题描述】:

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

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

【问题讨论】:

  • 不相关:您可以使用字符串格式创建网址:url = 'http://www.billboard.com/artists/top-100/{year}?page={page}'.format(year=random.randint(1958, 2013), page=random.randint(1, 5)) 注意:此代码与您的不同,包括两个端点。

标签: python beautifulsoup


【解决方案1】:

要获取具有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 未使用。

我只需要一个 img 标签。我怎样才能做到这一点?

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

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

【讨论】:

  • 现在,很好。但是,我只需要一个 img 标签。我该怎么做?
  • 你能检查一下我这样做是否正确吗,它仍然显示不止一个。 for img in div.find_all('img', alt=True): img = div.find('img', alt=True) print(img['alt'])
  • @BrianFuller:使用div.find() 代替 for-loop。
  • soup.findAll('div',{'class': 'thumbnail'}).img['alt']
【解决方案2】:

我想你的意思是:

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

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

【讨论】:

  • 不幸的是,我遇到了和以前一样的问题。什么都不显示。
  • 如果有人误解了,我可能应该补充一下。我想要img alt=''中的文字。
  • @BrianFuller 您的第一个findAll 可能有错误,其中没有名为'article' 的标签(或类似的东西,例如可能没有类'masonry-brick')。在快速检查one page 后,我看到很多'masonry-brick' 但没有标签'article'
  • @BrianFuller 哦,如果你想要里面的文字,那么soup.find('img').alt.text
  • 我收到错误AttributeError: 'NoneType' object has no attribute 'text'
猜你喜欢
  • 2013-01-11
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 2018-05-07
  • 1970-01-01
  • 2014-06-05
  • 2019-07-26
  • 2013-12-14
相关资源
最近更新 更多