2016-05-18 4 views
0

У меня есть следующий html из этого page.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>

Я хочу, чтобы поместить информацию в соответствии с первым Endorsements и Authorizations в список весь его сжатый вместе и быть в состоянии отличить ее от второй таблицы.

В списке это будет выглядеть так: ['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 первый, то для каждого tbody найти текст целевой td, например:

>>> 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']] 
Смежные вопросы