2017-11-23 6 views
1

私はPython3とBeautifulSoup 4.4.0を使ってウェブサイトからデータを抽出しています。私はdivタグのテーブルに興味がありますが、どのデータがテーブル内にあるのかを知るためには、h4タグのテキストを取得してから、テーブルである兄弟を取得する必要があります。問題は、内側に別のタグがある場合、h4タグの1つにスパンがあり、BeautifulSoupが文字列値としてNoneを返すことです。BeautifulSoup子どもなしの文字列でタグを見つける

def get_table_items(self, soup, header_title): 
     header = soup.find('h4', string=re.compile(r'\b{}\b'.format(header_title), re.I)) 
     header_table = header.find_next_sibling('table') 
     items = header_table.find_all('td') 
     return items 

あなたが正規表現に頼るよりも、手動ではなく、検索それを実行する必要があるかもしれません<h4>Unique Title 2<span>(<a href="...">Something</a>)</span></h4>

.... 
<div id="some_id"> 
    <h4>Unique Title 1</h4> 
    <table> 
    ... 
    </table> 
    <h4>Unique Title 2<span>(<a href="...">Something</a>)</span></h4> 
    <table> 
    ... 
    </table> 
    <h4>Unique Title 3</h4> 
    <table> 
    ... 
    </table> 
</div> 

答えて

1

を除くすべてのH4の作品上記のコード:

from bs4 import BeautifulSoup 

soup = BeautifulSoup(html, "html.parser") 
header_title = "Unique Title 2" 

for h4 in soup.find_all('h4'): 
    if header_title in h4.text: 
     ... 
関連する問題