2014-06-09 109 views
1

所有字符串與beautifulsoup 4比方說,我們有一個HTML文檔這樣的:編輯在HTML文檔在python

<html> 
<head> 
<title>title</title> 
</head> 
<body> 
<div class="c1">division 
    <p> 
    passage in division 
    <b>bold in passage </b> 
    </p> 
</div> 
</body> 
</html> 

我需要預先設置一個字「爽」到每個串 (或NavigableString在bs4術語中)在html文檔中。

我試圖通過每個元素,並檢查它是否有任何孩子,如果不是,然後編輯字符串。這是不準確的, 此外,編輯沒有任何影響。

回答

2

通過調用find_all()text=True參數,您可以找到文檔中的所有文本節點。使用replace_with()與修改後的文本替換文本節點:

from bs4 import BeautifulSoup 

html = """ 
<html> 
<head> 
<title>title</title> 
</head> 
<body> 
<div class="c1">division 
    <p> 
    passage in division 
    <b>bold in passage </b> 
    </p> 
</div> 
</body> 
</html> 
""" 

soup = BeautifulSoup(html) 
for element in soup.find_all(text=True): 
    text = element.string.strip() 
    if text: 
     element.replace_with("cool " + text) 

print soup.prettify() 

打印:

<html> 
<head> 
    <title> 
    cool title 
    </title> 
</head> 
<body> 
    <div class="c1"> 
    cool division 
    <p> 
    cool passage in division 
    <b> 
    cool bold in passage 
    </b> 
    </p> 
    </div> 
</body> 
</html> 
+0

真棒。有沒有辦法讓所有'