2017-10-05 1 views
0

私はこのコード行がありますBeautifulSoup3を使用してdivタグ内にあるスパンタグのテキストを選択するにはどうすればよいですか?

scoreline_div = soup.find("div", { "class" : "score-line" }) 

それは、ページ上のdivタグのページを選択し、これは、それは次のようになります。

<div class="score-line"><span class="home-team team team-900">South Africa</span><span class="score">27 - 27</span><span class="away-team team team-100">Australia</span></div> 

私は最初のテキストをどのように選択しないと、第3のspan(南アフリカ、オーストラリア)?また、スパンタグのクラスが変更されるので、classを検索せずにそれを実行して、最初の&第3スパンを選択するのではなく、

+0

が理由で、これらのスパンにアクセスできません彼らの位置? – RomanPerekhrest

+0

どのように? 'scoreline_div.span [0]'と打つことを意味しますか?それは動作しません、私にエラーを与える –

+0

'nth-of-type'セレクタで簡単に – RomanPerekhrest

答えて

1

あなたはfind_all()メソッドを使用して、スパンのリストを取得することができます。

scoreline_div = soup.find("div", { "class" : "score-line" }) 
spans = scoreline_div.find_all('span') 
# spans[0].text should return 'South Africa' 
# spans[2].text should return 'Australia' 
2

ワンラインソリューション:

s1,s2 = soup.find("div", { "class" : "score-line" }).select('span:nth-of-type(1),span:nth-of-type(3)') 
print(s1.text, s2.text) 

出力:

South Africa Australia 
関連する問題