1

これはかなり小さな質問で、以前の質問でほぼ解決されています。

問題は、今私がコメントの配列を持っていることですが、それは私が必要としているものではありません。コメントコンテンツの配列を取得します。そして、その間にhtmlを取得する必要があります。

次のようなものがあるとします。

<p>some html here<p>
<!-- begin mark -->
<p>Html i'm interested at.</p>
<p>More html i want to pull out of the document.</p>
<!-- end mark -->
<!-- begin mark -->
<p>This will be pulled later, but we will come to it when I get to pull the previous section.</p>
<!-- end mark -->

返信で、彼らはHTMLツリーのナビゲートに関するCrummyの説明を指摘していますが、私はそこに見つけられず、私の問題に答えませんでした。

何か案は?ありがとう。

PS。誰かがドキュメントでプロセスを数回繰り返すエレガントな方法を教えてくれたら、さらに称賛します。おそらくうまくいくかもしれませんが、うまくいきません:D

追加するために編集:

Martijn Pieters から提供された情報commentsを使用して、上記のコードを使用して取得した配列を、彼が設計したジェネレーター関数に渡す必要がありました。したがって、これはエラーになりません。

for elem in comments:
    htmlcode = allnext(comments)
    print htmlcode

配列を反復処理する前に、htmlcode コンテンツを操作できるようになると思います。

4

1 に答える 1

2

.next_siblingポインターを使用して、次の要素に移動できます。これを使用して、コメントに続くすべてのものを検索できますが、別のコメントは含まれません。

from bs4 import Comment

def allnext(comment):
    curr = comment
    while True:
        curr = curr.next_sibling
        if isinstance(curr, Comment):
            return
        yield curr

これはジェネレーター関数です。これを使用して、すべての「次の」要素を反復処理します。

for elem in allnext(comment):
    print elem

または、それを使用して、次のすべての要素のリストを作成できます。

elems = list(allnext(comment))

あなたの例は BeautifulSoup には少し小さすぎて、各コメントを<p>タグでラップしますが、元のターゲットからのスニペットを使用すると、www.gamespot.comこれはうまく機能します:

<div class="ad_wrap ad_wrap_dart"><div style="text-align:center;"><img alt="Advertisement" src="http://ads.com.com/Ads/common/advertisement.gif" style="display:block;height:10px;width:120px;margin:0 auto;"/></div>
<!-- start of gamespot gpt ad tag -->
<div id="div-gpt-ad-1359295192-lb-top">
<script type="text/javascript">
        googletag.display('div-gpt-ad-1359295192-lb-top');
    </script>
<noscript>
<a href="http://pubads.g.doubleclick.net/gampad/jump?iu=/6975/row/gamespot.com/home&amp;sz=728x90|970x66|970x150|970x250|960x150&amp;t=pos%3Dtop%26platform%3Ddesktop%26&amp;c=1359295192">
<img src="http://pubads.g.doubleclick.net/gampad/ad?iu=/6975/row/gamespot.com/home&amp;sz=728x90|970x66|970x150|970x250|960x150&amp;t=pos%3Dtop%26platform%3Ddesktop%26&amp;c=1359295192"/>
</a>
</noscript>
</div>
<!-- end of gamespot gpt tag -->
</div>

commentがそのスニペットの最初のコメントへの参照である場合、allnext()ジェネレーターは次のように表示します。

>>> list(allnext(comment))
[u'\n', <div id="div-gpt-ad-1359295192-lb-top">
<script type="text/javascript">
        googletag.display('div-gpt-ad-1359295192-lb-top');
    </script>
<noscript>
<a href="http://pubads.g.doubleclick.net/gampad/jump?iu=/6975/row/gamespot.com/home&amp;sz=728x90|970x66|970x150|970x250|960x150&amp;t=pos%3Dtop%26platform%3Ddesktop%26&amp;c=1359295192">
<img src="http://pubads.g.doubleclick.net/gampad/ad?iu=/6975/row/gamespot.com/home&amp;sz=728x90|970x66|970x150|970x250|960x150&amp;t=pos%3Dtop%26platform%3Ddesktop%26&amp;c=1359295192"/>
</a>
</noscript>
</div>, u'\n']
于 2013-01-27T13:53:43.340 に答える