【问题标题】:How to extract "alt" with text with Beautiful Soup如何使用 Beautiful Soup 提取带有文本的“alt”
【发布时间】:2017-04-24 03:42:17
【问题描述】:

我刚刚发现了 Beautiful Soup,它看起来非常强大。我想知道是否有一种简单的方法可以用文本提取“alt”字段。 一个简单的例子是

from bs4 import BeautifulSoup

html_doc ="""
<body>
<p>Among the different sections of the orchestra you will find:</p>
<p>A <img src="07fg03-violin.jpg" alt="violin" /> in the strings</p>
<p>A <img src="07fg03-trumpet.jpg" alt="trumpet"  /> in the brass</p>
<p>A <img src="07fg03-woodwinds.jpg" alt="clarinet and saxophone"/> in the woodwinds</p>
</body>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.get_text())

这会导致

在管弦乐队的不同部分中,您会发现:

字符串中的A

铜管家

木管乐器

但我希望在文本提取中包含 alt 字段,这样可以提供

在管弦乐队的不同部分中,您会发现:

弦乐中的小提琴

铜管中的小号

木管乐器中的单簧管和萨克斯管

谢谢

【问题讨论】:

标签: python beautifulsoup alt


【解决方案1】:

请考虑这种方法。

from bs4 import BeautifulSoup

html_doc ="""
<body>
<p>Among the different sections of the orchestra you will find:</p>
<p>A <img src="07fg03-violin.jpg" alt="violin" /> in the strings</p>
<p>A <img src="07fg03-trumpet.jpg" alt="trumpet"  /> in the brass</p>
<p>A <img src="07fg03-woodwinds.jpg" alt="clarinet and saxophone"/> in the woodwinds</p>
</body>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
ptag = soup.find_all('p')   # get all tags of type <p>

for tag in ptag:
    instrument = tag.find('img')    # search for <img>
    if instrument:  # if we found an <img> tag...
        # ...create a new string with the content of 'alt' in the middle if 'tag.text'
        temp = tag.text[:2] + instrument['alt'] + tag.text[2:]
        print(temp) # print
    else:   # if we haven't found an <img> tag we just print 'tag.text'
        print(tag.text)

输出是

Among the different sections of the orchestra you will find:
A violin in the strings
A trumpet in the brass
A clarinet and saxophone in the woodwinds

策略是:

  1. 查找所有&lt;p&gt;标签
  2. 在这些&lt;p&gt; 标签中搜索&lt;img&gt; 标签
  3. 如果我们找到&lt;img&gt;标签,将其alt属性的内容插入tag.text并打印出来
  4. 如果我们没有找到 &lt;img&gt; 标签,就打印出来

【讨论】:

  • 非常感谢@datell。它工作正常。还有一个问题。如果我在同一段落中有两张图片,例如

    在管弦乐队的不同部分中,您会发现:

    A 在弦乐中。一个 在铜管中

    一个 在木管乐器中

    ,那么它不会提取第二个。对同一段落中的 2 pr 更多“img”有任何想法吗?
【解决方案2】:
a = soup.findAll('img')

for every in a:
    print(every['alt'])

这样就可以了。

1.line 查找所有IMG(我们使用.findAll

或用于文本

print (a.text)
for eachline in a:
    print(eachline.text)

遍历每个结果的简单 for 循环或手动 soup.findAll('img')[0] 然后 soup.findAll('img')[1]..等等

【讨论】:

  • 谢谢,但您的代码返回小提琴小号单簧管和萨克斯管。这不是我的问题,根据我的原始帖子,我希望在“正确的位置”文本中包含这些内容。
猜你喜欢
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 2018-01-15
  • 2013-05-20
相关资源
最近更新 更多