2017-09-12 10 views
0

ここでは、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()) 

これを解決する方法上の任意のアイデア?

答えて

1

私は、より堅牢な方法を思いついた:

soup = BeautifulSoup(html, 'xml') 
tag_one = soup.find('a', {'name': 'One'}) 
tag_two = soup.find('a', {'name': 'Two'}) 

for tag in tag_one.next_elements: 
    if type(tag) is not bs4.element.Tag: 
     print(tag) 
    if tag is tag_two: 
     break 
1

find_all_nextメソッドを使用して、次のタグを反復処理し、stringsジェネレータを使用して各タグの文字列のリストを取得できます。

soup = BeautifulSoup(html, 'xml') 
tag_one = soup.find('a', {'name': 'One'}) 
tag_two = soup.find('a', {'name': 'Two'}) 
text = None 

for tag in tag_one.find_all_next(): 
    if tag is tag_two: 
     break 
    strings = list(tag.stripped_strings) 
    if strings and strings[0] != text: 
     text = strings[0] 
     print(text) 
関連する問題