Python - 使用beautifulsoup保存更改

时间:2017-07-06 05:42:17

标签: python html string python-3.x beautifulsoup

我使用Beautifulsoup解析html文件并检查文本是否为大写,在这种情况下我将其更改为小写。当我将输出保存到新的html文件时,没有反映更改。有人能指出我做错了什么。

def recursiveChildren(x):
    if "childGenerator" in dir(x):
      for child in x.childGenerator():
          name = getattr(child, "name", None)
          if name is not None:
             print(child.name)
          recursiveChildren(child)
    else:
      if not x.isspace():
         print (x)
         if(x.isupper()):
          x.string = x.lower()
          x=x.replace(x,x.string)

if __name__ == "__main__":
    with open("\path\) as fp:
      soup = BeautifulSoup(fp)
    for child in soup.childGenerator():
       recursiveChildren(child)
    html = soup.prettify("utf-8")
    with open("\path\") as file:
      file.write(html)

1 个答案:

答案 0 :(得分:0)

我不认为你的方式可以应对标记,如:

 <p>TEXT<span>More Text<i>TEXT</i>TEXT</span>TEXT</p>

你想要的方法是replaceWith()而不是replace()。您还没有打开文件进行写作。

这就是我的方式。

from bs4 import BeautifulSoup

filename = "test.html"
if __name__ == "__main__":
    # Open the file.
    with open(filename, "r") as fp:
        soup = BeautifulSoup(fp, "html.parser") # Or BeautifulSoup(fp, "lxml")
        # Iterate over all the text found in the document.
        for txt in soup.findAll(text=True):
            # If all the case-based characters (letters) of the string are uppercase.
            if txt.isupper(): 
                # Replace with lowercase.
                txt.replaceWith(txt.lower())
    # Write the file.
    with open(filename, "wb") as file:
        file.write(soup.prettify("utf-8"))