親タグにマーカーが含まれている場合は、親タグを取得したいと思います。たとえば、MARKER とします。たとえば、私は持っています:
<a>
<b>
<c>
MARKER
</c>
</b>
<b>
<c>
MARKER
MARKER
</c>
</b>
<b>
<c>
stuff
</c>
</b>
</a>
私はつかみたい:
<b>
<c>
MARKER
</c>
</b>
<b>
<c>
MARKER
MARKER
</c>
</b>
私の現在のコードは次のとおりです。
for stuff in soup.find_all(text=re.compile("MARKER")):
post = stuff.find_parent("b")
これは機能しますが、次のようになります。
<b>
<c>
MARKER
</c>
</b>
<b>
<c>
MARKER
MARKER
</c>
</b>
<b>
<c>
MARKER
MARKER
</c>
</b>
これが発生する理由は明らかです。見つかった MARKER ごとに、含まれているタグ全体を 1 回印刷しているため、2 つの MARKER を含むタグが 2 回印刷されます。ただし、完了後に指定されたタグ内を検索しないように BeautifulSoup に指示する方法がわかりません (具体的には、実行できないと思いますか?) または、おそらくすべてを辞書にインデックス付けして重複を拒否する以外に、これを防ぐ方法がわかりません?
編集:これは、何らかの理由で、削除されたバージョンであるにもかかわらず、上記が実際にエラーを生成しないため、私が取り組んでいる特定のケースです。(誰かが興味を持っている場合は、投稿ごとにフェッチしている特定のフォーラム スレッド。)
from bs4 import BeautifulSoup
import urllib.request
import re
url = 'http://forums.spacebattles.com/threads/asukaquest-3-starfish-eater.258271/page-179'
soup = urllib.request.urlopen(url).read()
sbsoup = BeautifulSoup(soup)
for stuff in sbsoup.find_all(text=re.compile("\[[Xx]\]")):
post = stuff.find_parent("li")
print(post.find("a", class_="username").string)
print(post.find("blockquote", class_="messageText ugc baseHtml").get_text())