【问题标题】:Python - Save back changes using beautifulsoupPython - 使用 beautifulsoup 保存更改
【发布时间】:2017-07-07 21:02:48
【问题描述】:

我使用 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)

【问题讨论】:

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


    【解决方案1】:

    我认为您的方式无法处理以下标记:

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

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 2012-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      相关资源
      最近更新 更多