2017-04-24 55 views
2

我剛剛發現了美麗的湯,這似乎很強大。我想知道是否有一種簡單的方法來提取文本「alt」字段。 一個簡單的例子是如何用美麗的湯提取文字「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木管樂器

但我想有字符提取,這將使

其中管絃樂隊的不同部分內中高音場,你會發現:

小提琴的琴絃

在小號黃銅

甲單簧管和薩克斯在木管樂器

由於

+0

看一看:http://stackoverflow.com/questions/2612548/extracting -an-attribute-value-with-beautifulsoup – JacobIRR

回答

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. 找到所有<p>標籤
  2. 搜索的<img>標籤在這些<p>標籤
  3. 如果我們發現與<img>標籤插入co其alt屬性到tag.text和ntent打印出來
  4. 如果我們沒有找到一個<img>標籤只是打印出來
+0

非常感謝@datell。它工作正常。還有一個問題。如果我在同一段中有兩個圖像,例如

在管絃樂隊的不同部分中,您會發現:

A violin中的字符串。在黃銅

clarinet and saxophonetrumpet在木管樂器

,那就不能提取第二個。任何關於2 pr更多「img」在同一段中的想法? – Portland

0
a = soup.findAll('img') 

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

這將完成這項工作。

1.line找到所有的IMG(我們使用.find 所有

或文本

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

簡單的for循環,通過每一結果或手動soup.findAll('img')[0]然後 去soup.findAll('img')[1] ..等等

+0

謝謝,但你的代碼返回小提琴 小號 單簧管和薩克斯管。這不是我的問題,我想根據我原來的帖子,將這些內容放在「正確的地方」。 – Portland