Python BeautifulSoup 获取多个表格中相同class的td值
您好,如果您想要获取多个表格中td class一样的td值,可以使用以下代码:
from bs4 import BeautifulSoup
html = '''
<table>
<tr>
<td class="class1">Value 1</td>
<td class="class2">Value 2</td>
</tr>
<tr>
<td class="class1">Value 3</td>
<td class="class2">Value 4</td>
</tr>
</table>
<table>
<tr>
<td class="class1">Value 5</td>
<td class="class2">Value 6</td>
</tr>
<tr>
<td class="class1">Value 7</td>
<td class="class2">Value 8</td>
</tr>
</table>
'''
soup = BeautifulSoup(html, 'html.parser')
td_values = []
td_class = 'class1'
tables = soup.find_all('table')
for table in tables:
tds = table.find_all('td', class_=td_class)
for td in tds:
td_values.append(td.text)
print(td_values)
输出结果为:['Value 1', 'Value 3', 'Value 5', 'Value 7']
这段代码首先使用BeautifulSoup库将HTML解析为BeautifulSoup对象。然后,通过find_all方法找到所有的table标签,并依次遍历每个table。在每个table中,使用find_all方法找到td标签中class为指定类名的td,并将其文本值添加到td_values列表中。最后,输出td_values列表中的值。
希望对您有帮助!
原文地址: https://www.cveoy.top/t/topic/pEbP 著作权归作者所有。请勿转载和采集!