如何从此 html 数据中检索所有 td
信息:
<h1>All staff</h1>
<h2>Manager</h2>
<table class="StaffList">
<tbody>
<tr>
<th>Name</th>
<th>Post title</th>
<th>Telephone</th>
<th>Email</th>
</tr>
<tr>
<td>
<a href="http://profiles.strx.usc.com/Profile.aspx?Id=Jon.Staut">Jon Staut</a>
</td>
<td>Line Manager</td>
<td>0160 315 3832</td>
<td>
<a href="mailto:Jon.staut@strx.usc.com">Jon.staut@strx.usc.com</a> </td>
</tr>
</tbody>
</table>
<h2>Junior Staff</h2>
<table class="StaffList">
<tbody>
<tr>
<th>Name</th>
<th>Post title</th>
<th>Telephone</th>
<th>Email</th>
</tr>
<tr>
<td>
<a href="http://profiles.strx.usc.com/Profile.aspx?Id=Peter.Boone">Peter Boone</a>
</td>
<td>Mailer</td>
<td>0160 315 3834</td>
<td>
<a href="mailto:Peter.Boone@strx.usc.com">Peter.Boone@strx.usc.com </a>
</td>
</tr>
<tr>
<td>
<a href="http://profiles.strx.usc.com/Profile.aspx?Id=John.Peters">John Peters</a>
</td>
<td>Builder</td>
<td>0160 315 3837</td>
<td>
<a href="mailto:John.Peters@strx.usc.com">John.Peters@strx.usc.com</a>
</td>
</tr>
</tbody>
</table>
这是我生成错误的代码:
response =requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.findAll('table', attrs={'class': 'StaffList'})
list_of_rows = []
for row in table.findAll('tr'): #2 rows found in table -loop through
list_of_cells = []
for cell in row.findAll('td'): # each cell in in a row
text = cell.text.replace(' ','')
list_of_cells.append(text)
#print list_of_cells
list_of_rows.append(list_of_cells)
#print all cells in the two rows
print list_of_rows
错误消息:
AttributeError: 'ResultSet' object has no attribute 'findAll'
我需要做什么才能让代码输出两个web表中的所有信息?
最佳答案
问题从这一行开始:
table = soup.findAll('table', attrs={'class': 'StaffList'})
findAll
返回一个没有属性 findAll
的数组。
只需将 findAll
更改为 find
:
table = soup.find('table', attrs={'class': 'StaffList'})
关于python - 从网络数据中提取两个表的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36666074/