[英]Beautiful Soup Get data for first table in a div
I am trying to get the data for the first table from a div containing many tables, how do I do it? 我正在尝试从包含许多表的div中获取第一个表的数据,该怎么办?
<div class="mainCont port_hold ">
<table class="tblpor">
<tr><th>Company</th><th>Code</th></tr>
<tr><td>ABC </td><td>1234</td></tr>
<tr><td>XYZ </td><td>6789</td></tr>
</table>
<table class="tblpor MT25">
<tr><th>Company</th><th>Industry</th></tr>
<tr><td>ABCDEF </td><td>aaaaa </td></tr>
<tr><td>STUVWX </td><td>bbbbb </td></tr>
</table>
</div>
I need the data for table class="tblpor" and following is the code I created, however it gives me the data for all the tables inside the div. 我需要表class =“ tblpor”的数据,以下是我创建的代码,但是它为我提供了div中所有表的数据。
for x in soup2.find('table', class_='tblpor'):
for y in soup2.findAll('tr'):
for z in soup2.findAll('td'):
print(z.text)
Please help. 请帮忙。
Regards, babsdoc 问候,babsdoc
You can select the first table using css selector like so. 您可以像这样使用css选择器选择第一个表。
first_table = soup.select_one("table:nth-of-type(1)")
Carrying on from here to extract data in the cells for each row is straightforward. 从这里继续提取每一行单元格中的数据很简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.