Python使用beautifulsoup保存更改

2024-09-30 01:34:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件nameinnonechildforstringif
1条回答
网友
1楼 · 发布于 2024-09-30 01:34:18

我不认为您的方法可以处理如下标记:

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

另外,您需要的方法是replaceWith()而不是replace()。您尚未打开文件进行写入。

我就是这样做的。

^{pr2}$

相关问题 更多 >

    热门问题