2016-05-18 14 views
0

私はこのpageから以下のhtmlを持っています。xpathの後続兄弟とテーブル内の要素のグループ化

<tbody><tr> 
 
<td align="center" class="column_heading" width="200" title="The following are the Endorsements for the above license.">Endorsements</td><td align="center" class="column_heading" width="150" title="See Authorization Level Codes with their description at the bottom of the page.">Authorization Level(s) *</td></tr> 
 
<tr><td align="center" bgcolor="#8AFF8A" class="section_detail">Health Education</td> 
 
<td align="center" bgcolor="#FFFFCC" class="section_detail">HS</td></tr><tr><td align="center" bgcolor="#8AFF8A" class="section_detail">Physical Education</td> 
 
<td align="center" bgcolor="#FFFFCC" class="section_detail">ML/HS 
 
</td></tr></tbody> 
 

 
<tbody><tr> 
 
<td align="center" class="column_heading" width="200" title="The following are the Endorsements for the above license.">Endorsements</td><td align="center" class="column_heading" width="150" title="See Authorization Level Codes with their description at the bottom of the page.">Authorization Level(s) *</td></tr> 
 
<tr><td align="center" bgcolor="#8AFF8A" class="section_detail">School Counselor</td> 
 
<td align="center" bgcolor="#FFFFCC" class="section_detail">ML/HS C 
 
</td></tr></tbody>

私はすべて一緒に圧縮し、第二のテーブルからそれを区別することができ、リストに最初EndorsementsAuthorizations下の情報を載せていきたいと思います。

リストでは、次のようになります。 ['Health Education', 'HS', Physical Education', 'ML/HS\r'], ['School Counselor', 'ML/HS C\r']

私が今取得しているのは、 ['Health Education', 'HS'], ['Physical Education', 'ML/HS\r'], ['School Counselor', 'ML/HS C\r']です。

私のコードの短いバージョンは次のとおりです。どこへ行く

test2 = tree.xpath(".//tr[td = 'Endorsements']/following-sibling::tr") 
endorse1.append(test2) 

答えて

1

一つの方法は、td背景色である、あなたは印刷するとき、それはあなたがフォームに必要情報を返す必要があり、これはアウト切り取らしてみてくださいタプルの

everything=[] 
for tr in tree.xpath("//tr[td[@class='section_detail']]"): 
    row={} 
    row['endorsement']=tr.xpath("td[@bgcolor='#8AFF8A']") 
    row['auth']=tr.xpath("td[@bgcolor='#FFFFCC']") 
    everything.append(row) 
1

あなたがテーブル/ TBODYあたりのグループの結果にしたいので、例えば、各tbodyのためにターゲットtdテキストを見つけ、最初tbodyのリストを取得:

>>> tables = tree.xpath("//tbody[tr/td = 'Endorsements']") 
>>> result = [t.xpath("tr[td = 'Endorsements']/following-sibling::tr/td/text()") \ 
...    for t in tables] 
... 
>>> print result 
[['Health Education', 'HS', 'Physical Education', 'ML/HS'], ['School Counselor', 'ML/HS C']] 
関連する問題