2017-07-06 20 views
0

Beautifulsoupを使用してhtmlファイルを解析し、テキストが大文字であるかどうかをチェックします。その場合、小文字に変更します。出力を新しいhtmlファイルに保存すると、変更は反映されません。誰かが私が間違っていることを指摘できますか?Python - beautifulsoupを使用して変更を保存する

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) 

答えて

0

私はあなたの方法は次のようにマークアップに対処するとは思わない。)(交換しないで)あなたが望む方法でreplaceWith(あるまた

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

。あなたは書き込みのためにファイルを開いていません。

これは私がやる方法です。

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")) 
関連する問題