1

できれば BeautifulSoup を使用して、HTML ドキュメント内のテキスト文字列へのすべてのパスを生成するにはどうすればよいですか? 私はこのコードを持っています:

<DIV class="art-info"><SPAN class="time"><SPAN class="time-date" content="2012-02-28T14:46CET" itemprop="datePublished">
             28. february 2012
            </SPAN>
            14:46
           </SPAN></DIV><DIV>
           Something,<P>something else</P>continuing.
          </DIV>

HTMLコードをテキスト文字列へのパスに分割したいのですが、

str1 >>>  <DIV class="art-info"><SPAN class="time"><SPAN class="time-date" content="2012-02-28T14:46CET" itemprop="datePublished">28. february 2012</SPAN></SPAN></DIV>
str2 >>>  <DIV class="art-info"><SPAN class="time">14:46</SPAN></DIV>
str3 >>>  <DIV>Something,continuing.</DIV>
str4 >>>  <DIV><P>something else</P></DIV>

また

str1 >>>  <DIV><SPAN><SPAN>28. february 2012</SPAN></SPAN></DIV>
str2 >>>  <DIV><SPAN>14:46</SPAN></DIV>
str3 >>>  <DIV>Something,continuing.</DIV>
str4 >>>  <DIV><P>something else</P></DIV>

また

str1 >>>  //div/span/span/28. february
str2 >>>  //div/span/14:46
str3 >>>  //div/Something,continuing.
str4 >>>  //div/p/something else

BeautifulSoup のドキュメントを調べましたが、その方法がわかりません。あなたはなにか考えはありますか?

4

1 に答える 1

2
from bs4 import BeautifulSoup
import re
file=open("input")
soup = BeautifulSoup(file)
for t in soup(text=re.compile(".")):
  path = '/'.join(reversed([p.name for p in t.parentGenerator() if p]))
  print path+"/"+ t.strip()

出力

[document]/html/body/div/span/span/28. february 2012
[document]/html/body/div/span/14:46
[document]/html/body/div/Something,
[document]/html/body/div/p/something else
[document]/html/body/div/continuing.
于 2013-03-29T00:27:47.160 に答える