问题
here is the HTML content:
<table cellspacing="1" cellpadding="0" class="data">
<tr class="colhead">
<th colspan="3">Expression</th>
</tr>
<tr class="colhead">
<th>Task</th>
<th>Action</th>
<th>List</th>
</tr>
<tr class="rowLight">
<td width="40%">
Task1
</td>
<td width="20%">
Assigned to
</td>
<td width="40%">
Harry
</td>
</tr>
<tr class="rowDark">
<td width="40%">
Task2
</td>
<td width="20%">
Rejected by
</td>
<td width="40%">
Lopa
</td>
</tr>
<tr class="rowLight">
<td width="40%">
Task5
</td>
<td width="20%">
Accepted By
</td>
<td width="40%">
Mathew
</td>
</tr>
Now I have to get the values as below : (the below table is nothing but an Excel table,that i will build up,once reached to the values.)
Task Action List
Task1 Assigned to Harry
Task2 Rejected by Lopa
Task5 Accepted By Mathew
A lay man solution what I know as below:
from bs4 import BeautifulSoup
soup = BeautifulSoup(source_URL)
alltables = soup.findAll( "table", {"border":"2", "width":"100%"} )
t = [x for x in soup.findAll('td')]
[x.renderContents().strip('\n') for x in t]
But in my above HTML content such structure not present,so how to approach? Please guide me here!
回答1:
Use .stripped_strings to get the 'interesting' text from a table row:
rows = table.find_all('tr', class_=('rowLight', 'rowDark'))
for row in rows:
print list(row.stripped_strings)
This outputs:
[u'Task1', u'Assigned to', u'Harry']
[u'Task2', u'Rejected by', u'Lopa']
[u'Task5', u'Accepted By', u'Mathew']
or, to pull everything into one list of lists (with, by request, the last row not included):
data = [list(r.stripped_strings) for r in rows[:-1]]
which becomes:
data = [[u'Task1', u'Assigned to', u'Harry'], [u'Task2', u'Rejected by', u'Lopa']]
The result of .find_all(), a ResultSet, acts just like a Python list and you can slice it at will to ignore certain rows, for example.
来源:https://stackoverflow.com/questions/14156546/confusion-to-read-html-table-contents-using-beautifulsoup