2016-05-18 5 views
0

Ich habe die folgende HTML aus dieser page.xpath following-gleichgeordnete und Gruppierung wie Elemente in einer Tabelle

<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>

Ich möchte die Informationen unter dem ersten Endorsements und Authorizations in eine Liste Reißverschluss alle zusammen und zu können, um es aus der zweiten Tabelle zu unterscheiden. In einer Liste würde es so aussehen: ['Health Education', 'HS', Physical Education', 'ML/HS\r'], ['School Counselor', 'ML/HS C\r'].

Was ich jetzt bekomme, ist dies: ['Health Education', 'HS'], ['Physical Education', 'ML/HS\r'], ['School Counselor', 'ML/HS C\r'].

Die kurze Version meines Codes ist:

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

Antwort

1

Ein Weg durch die td Hintergrundfarben zu gehen, versuchen Sie dies snipped aus, wenn Sie drucken, sollte es die Informationen zurück, die Sie in einer Form möchten Tupel.

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

Sie möchten Konzernergebnis pro Tisch/tbody, so erhalten Liste der tbody zuerst, dann für jeden tbody das Ziel td Text finden, zum Beispiel:

>>> 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']] 
Verwandte Themen