2016-12-04 1 views
2

私は2012年のオバマ・ロムニー大統領議論から引用を抽出しようとしています。問題はthe siteで整理されていません。だから、構造は次のようになります。あなたの子供や兄弟に応じてBeautifulSoupを使ってタグを選択するにはどうすればよいですか?

<span class="displaytext"> 
    <p> 
     <i>OBAMA</i>Obama's first quotes 
    </p> 
    <p>More quotes from Obama</p> 
    <p>Some more Obama quotes</p> 

    <p> 
     <i>Moderator</i>Moderator's quotes 
    </p> 
    <p>Some more quotes</p> 

    <p> 
     <i>ROMNEY</i>Romney's quotes 
    </p> 
    <p>More quotes from Romney</p> 
    <p>Some more Romney quotes</p> 
</span> 

は、最初の子、あなたがその最初の子iで次のpを打つまではp兄弟だテキストOBAMAし、すべてを持っているiある<p>を選択する方法はありますテキストはありませんObama ??ここで

私がこれまで試したものですが、それだけで私だけがfinite state machine様液の種類はここで働いなると思いObama's first quotes

答えて

2

を出力兄弟

input = '''<span class="displaytext"> 
     <p> 
      <i>OBAMA</i>Obama's first quotes 
     </p> 
     <p>More quotes from Obama</p> 
     <p>Some more Obama quotes</p> 

     <p> 
      <i>Moderator</i>Moderator's quotes 
     </p> 
     <p>Some more quotes</p> 

     <p> 
      <i>ROMNEY</i>Romney's quotes 
     </p> 
     <p>More quotes from Romney</p> 
     <p>Some more Romney quotes</p> 
     </span>''' 

soup = BeautifulSoup(input) 
debate_text = soup.find("span", { "class" : "displaytext" }) 
president_quotes = debate_text.find_all("i", text="OBAMA") 

for i in president_quotes: 
    siblings = i.next_siblings 
    for sibling in siblings: 
     print(sibling) 

を無視して最初のpをつかんれます。このように:

soup = BeautifulSoup(input, 'lxml') 
debate_text = soup.find("span", { "class" : "displaytext" }) 
obama_is_on = False 
obama_tags = [] 
for p in debate_text("p"): 
    if p.i and 'OBAMA' in p.i: 
     # assuming <i> is used only to indicate speaker 
     obama_is_on = True 
    if p.i and 'OBAMA' not in p.i: 
     obama_is_on = False 
     continue 
    if obama_is_on: 
     obama_tags.append(p) 
print(obama_tags) 

[<p> 
<i>OBAMA</i>Obama's first quotes 
     </p>, <p>More quotes from Obama</p>, <p>Some more Obama quotes</p>] 
2

あなたはiの親の兄弟を見つける必要がありますので、他のオバマ氏の引用符は、p、ないiの兄弟です。あなたがそれらの兄弟をループしているとき、あなたがiを持っているときに停止することができます。このような何か:

for i in president_quotes: 
    print(i.next_sibling) 
    siblings = i.parent.find_next_siblings('p') 
    for sibling in siblings: 
     if sibling.find("i"): 
      break 
     print(sibling.string) 

出力します

Obama's first quotes 

More quotes from Obama 
Some more Obama quotes 
関連する問題