2011-09-14 11 views
0

私はBeautifulSoupを使用して、htmlファイル内のすべてのカンマを‚に置き換えています。これは私のコードです:BeautifulSoup htmlファイルを解析するpython

f = open(sys.argv[1],"r") 
data = f.read() 

soup = BeautifulSoup(data) 

comma = re.compile(',') 


for t in soup.findAll(text=comma): 
     t.replaceWith(t.replace(',', '‚')) 

このコードは、HTMLファイルにいくつかのJavaScriptが含まれている場合を除いて動作します。その場合、コンマ(、)はjavascriptコードに置き換えられます。これは必須ではない。私は、htmlファイルのすべてのテキストコンテンツを置き換えたいだけです。

答えて

5

soup.findallは、呼び出し可能なを取ることができます:

tags_to_skip = set(["script", "style"]) 
# Add to this list as needed 

def valid_tags(tag): 
    """Filter tags on the basis of their tag names 

    If the tag name is found in ``tags_to_skip`` then 
    the tag is dropped. Otherwise, it is kept. 
    """ 
    if tag.source.name.lower() not in tags_to_skip: 
     return True 
    else: 
     return False 

for t in soup.findAll(valid_tags): 
    t.replaceWith(t.replace(',', '‚')) 
+0

クールな...それは素晴らしいです。コメントをスキップするにはどうしたらいいですか? <!Doctype ....>も表示されます。htmlファイルのコメント部分に置き換える必要はありません。 – Divya

+0

もしあなたが '' BeautifulSoup'をインポートしたら、 BeautifulSoup .__ version__を印刷すると、どのバージョン番号が返されますか? –

関連する問題