2015-09-14 36 views
1
........<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; text-indent:0px;">textHere 

<span style=" font-family:'Noto Sans';">ABC</span></p> 

<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; text-indent:0px;"><span style=" font....... 

我有一個類似上面的HTML。我需要BeautifulSoup:如何用span標記替換內容

  1. 找到「能登三世」 FONT-FAMILY的所有內容(他們總是span標記內)
  2. 用了變化休息替換它們(A爲X,B爲Y等...)代碼

我試過的是這個,但不能正常工作。

from bs4 import BeautifulSoup 
source_code = """.....<span style=" font-family:'Noto Sans';">ABC</span></p>......"" 
soup = BeautifulSoup(source_code, "lxml") 

for re in soup.findAll('font', 'face' = "Noto Sans"): 
    print (re.replace("A", "X")) 

有什麼想法?

回答

1

你需要找到具有font-family: Noto Sans內的所有span標籤,然後用X更換Aspan元素裏,你已經發現:

import re 

from bs4 import BeautifulSoup 


source_code = """.....<span style=" font-family:'Noto Sans';">ABC</span></p>......"""  
soup = BeautifulSoup(source_code, "lxml") 

for elm in soup.find_all('span', style=re.compile(r"font-family:'Noto Sans'")): 
    elm.string = elm.text.replace("A", "X") 

print(soup.prettify()) 

打印:

<span style=" font-family:'Noto Sans';"> 
XBC 
</span> 
+0

這工作得很好。謝謝! – PVGM

相關問題