2016-12-10 3 views
0

私はWikipediaのページをスクラップしようとしています。また、単純な問題に直面し、解決策を見つけることができません。 thとtdの2つのタグが隣にあります。また、両方とも独立しています。私は1つのタグのテキストを他のタグの値に基づいて取得したい(お互いに独立している)。pythonのスクラップで、すぐ隣にある独立したタグを見つける

<th scope="row" style="white-space:nowrap;padding-right:0.65em;">Budget</th> 
<td style="line-height:1.3em;">$200 million<sup id="cite_ref-3" class="reference"><a href="#cite_note-3">[3]</a></sup></td> 

私は($ 2億で)「TD」タグの値を取得したいが、番目の 'タグのテキストは、[予算]で、場合:ここで

は一例です。唯一の対応は「お互いの隣に」ということです。アウト

+0

URLを投稿参考になります –

答えて

0
from bs4 import BeautifulSoup 

html = '''<th scope="row" style="white-space:nowrap;padding-right:0.65em;">Budget</th> 
<td style="line-height:1.3em;">$200 million<sup id="cite_ref-3" class="reference"><a href="#cite_note-3">[3]</a></sup></td>''' 

soup = BeautifulSoup(html, 'lxml') 
td_text = soup.find(lambda tag: tag.name=='td' and 'Budget' in tag.parent.text).text 
print(td_text) 

$200 million[3] 
関連する問題