簡體   English   中英

Python-使用beautifulsoup保存更改

[英]Python - Save back changes using 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)

我認為您的方式無法應對像這樣的標記:

 <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"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM