2017-05-13 14 views
2

BeautifulSoupを使用して単語のリストをスパンに変換する必要があります。例えばBeautifulSoupを使用して単語をスパンで囲むにはどうすればよいですか?

<html><body>word-one word-two word-one</body></html> 

にする必要があるword-oneニーズが

は、これまでのところ、私が使用してこれらの要素を見つけることができる午前スパンに移動する

<html><body><span>word-one</span> word-two <span>word-one</span></body></html> 

for html_element in soup(text=re.compile('word-one')): 
    print(html_element) 

しかし、そのようなテキストをスパンに置き換えることは明確ではありません。

+0

あなたは['lxml'](http://lxml.de/)も使用していますか? [python lxmlの別の要素の後に要素を追加する]を参照してください(https://stackoverflow.com/questions/7474972/python-lxml-append-element-after-another-element) –

+0

BSを試してみるだけで、簡単に見つけることができます。 – Nishant

答えて

4

私は変数htmlがコード<html><body>word-one word-two word-one</body></html>であり、テキストとコードを分けてそれらを一緒に追加しました。

soup = BeautifulSoup(html,'html.parser') 
text = soup.text # Only the text from the soup 

soup.body.clear() #Clear the text between the body tags 

new_text = text.split() # Split beacuse of the spaces much easier 

for i in new_text: 
    new_tag = soup.new_tag('span') #Create a new tag 
    new_tag.append(i) #Append i to it (from the list that's split between spaces) 
    #example new_tag('a') when we append 'word' to it it will look like <a>word</a> 
    soup.body.append(new_tag) #Append the whole tag e.g. <span>one-word</span) 

正規表現では、これをいくつかの単語に一致させることもできます。

soup = BeautifulSoup(html, 'html.parser') 
text = soup.text # Only the text from the soup 

soup.body.clear() # Clear the text between the body tags 

theword = re.search(r'\w+', text) # Match any word in text 
begining, end = theword.start(), theword.end() 

soup.body.append(text[:begining]) # We add the text before the match 

new_tag = soup.new_tag('span') # Create a new tag 

new_tag.append(text[begining:end]) 
# We add the word that we matched in between the new tag 
soup.body.append(new_tag) # We append the whole text including the tag 
soup.body.append(text[end:]) # Append everything that's left 

同様の方法で.insertを使用できると確信しています。

+0

これを好きなら、divなどの重要なタグをいくつか失うことはありませんか?私はそれらをスパンしたいが、divやpやテーブルのことを妨げないことを意味する。 – Nishant

+0

あなたは何を意味するのかよくわからない。あなたは私にHTMLを与えて、このような場合にあなたにやってもらう方法を与えた。 あなたはおそらく実際のウェブサイトでそれをやっているでしょうから、親タグを閉じて同じことをしなければなりません。例:a = soup.find( 'p')、次にa.div.clearの間にすべてをクリアすると、何が起きているのかを理解できるようにコメントを付けました。より簡単であれば、それぞれのためのbeautifulsoupドキュメントを参照できるコードを理解してください。 –

+0

明確にしたい。体もdivを持っていると想像してください。テキストを取ってクリアしてもうまくいきませんか?とにかくこれにはたくさんのアイデアがあります。 – Nishant

関連する問題