Skip to main content
 首页 » 编程设计

python之使用 BeautifulSoup 调整 DOM 树中的所有文本

2024年10月25日10daizhj

我正在尝试将 HTML 文件中的所有(用户可见的)文本大写。这是显而易见的事情:

from bs4 import BeautifulSoup 
 
def upcaseAll(str): 
    soup = BeautifulSoup(str) 
    for tag in soup.find_all(True): 
        for s in tag.strings: 
            s.replace_with(unicode(s).upper()) 
    return unicode(soup) 

崩溃了:

File "/Users/malvolio/flip.py", line 23, in upcaseAll 
    for s in tag.strings: 
  File "/Library/Python/2.7/site-packages/bs4/element.py", line 827, in _all_strings 
    for descendant in self.descendants: 
  File "/Library/Python/2.7/site-packages/bs4/element.py", line 1198, in descendants 
    current = current.next_element 
AttributeError: 'NoneType' object has no attribute 'next_element' 

我能想到的所有变体都以同样的方式崩溃。 BS4 似乎不喜欢我替换了很多 NavigableStrings。我该怎么做?

请您参考如下方法:

你不应该使用 str 作为函数参数,因为这是 python 内置的影子名称。

您还应该能够通过使用 prettify 和 formatter 来转换可见元素,如下所示:

... 
return soup.prettify(formatter=lambda x: unicode(x).upper()) 

我已经测试过了,它可以工作:

from bs4 import BeautifulSoup 
 
import requests 
 
r = requests.get('http://www.stackoverflow.com') 
 
soup = BeautifulSoup(r.content) 
 
print soup.prettify(formatter=lambda x: unicode(x).upper())[:200] 
<!DOCTYPE html> 
<html> 
 <head> 
  <title> 
   STACK OVERFLOW 
  </title> 
  <link href="//CDN.SSTATIC.NET/STACKOVERFLOW/IMG/FAVICON.ICO?V=00A326F96F68" rel="SHORTCUT ICON"/> 
  <link href="//CDN.SSTATIC.NE 
  ... 

您可以阅读 OUTPUT FORMATTER获取更多详细信息。

希望这对您有所帮助。