我刚刚发现了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
黄铜中的A
木管乐器中的A
但我希望在文本提取中包含 alt 字段,这会给出
在乐团的不同部分中,您会发现:
弦上的 fiddle
铜管中的喇叭
木管乐器中的单簧管和萨克斯管
谢谢
请您参考如下方法:
请考虑这种方法。
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
策略是:
- 查找所有
<p>标签 - 搜索
<img>在这些<p>中标记标签 - 如果我们找到并且
<img>标签插入其alt的内容属性进入tag.text并打印出来 - 如果我们找不到
<img>tag 打印出来
