ここでは、xml
パーサを使用してBeautifulSoup4(Python 3)を使用してスクレイプしようとしている「現実の」HTMLファイルのスニペットを示します私が働いている汚れたhtmlファイルの一種)で:BeautifulSoup4を使用して異なるレベルの2つのタグ間でテキストを取得する
<html>
<p> Hello </p>
<a name='One'>Item One</a>
<p> Text that I would like to scrape. </p>
<p> More text I would like to scrape.
<table>
<tr>
<td>
<a name='Two'>Item Two</a>
</td>
</tr>
</table>
A bunch of text that shouldn't be scraped.
More text.
And more text.
</p>
</html>
私の目標は、すべてのテキストが最後<p>
のテキストの3行をこすることなく、<a name='One'>Item One</a>
と<a name='Two'>Item Two</a>
の間に座っこすりすることです。
私はfind_next()
機能を使用して第1 <a>
タグからトラバースしようと試みたし、その後get_text()
を呼び出すことが、私は最後の<p>
を打ったときに発生するものではありませんこれは、最後のテキストも掻き取ってしまうことですしましたが欲しいです。
サンプルコード:
tag_one = soup.find('a', {'name': 'One'})
tag_two = soup.find('a', {'name': 'Two'})
found = False
tag = tag_one
while found == False:
tag = tag.find_next()
if tag == tag_two:
found = True
print(tag.get_text())
これを解決する方法上の任意のアイデア?