Python 美丽的汤提取特定列
慢慢地学习python和其他语言,但却被这一点难住了 我正在尝试从以下布局中提取第一列和第四列数据(缩小大小) 该文件存储在本地,目前我有一个补丁的代码从其他类似的问题,我无法得到工作Python 美丽的汤提取特定列,python,html-parsing,beautifulsoup,Python,Html Parsing,Beautifulsoup,慢慢地学习python和其他语言,但却被这一点难住了 我正在尝试从以下布局中提取第一列和第四列数据(缩小大小) 该文件存储在本地,目前我有一个补丁的代码从其他类似的问题,我无法得到工作 for row in soup.find('table')[0]body.findall('tr'): first_column = row.findAll('td')[0].contents third_column = row.findAll('td')[3].contents print (first_c
for row in soup.find('table')[0]body.findall('tr'):
first_column = row.findAll('td')[0].contents
third_column = row.findAll('td')[3].contents
print (first_column, third_column)
您的代码存在多个错误。这一行:
soup.find('table')[0]body.findall('tr'):
毫无意义。当您使用find
时,它返回一个BS对象。不能在单个对象上使用索引访问元素。无论您在哪里使用findAll
,它都会返回一个BS对象列表。这意味着您必须在其上循环以获得单个元素。这就是for循环体不能按预期工作的原因
以下是获得所需内容的代码:
from bs4 import BeautifulSoup
html_file = open('html_file')
soup = BeautifulSoup(html_file)
table = soup.findAll('table')[0]
rows = table.findAll('tr')
first_columns = []
third_columns = []
for row in rows[1:]:
first_columns.append(row.findAll('td')[0])
third_columns.append(row.findAll('td')[2])
for first, third in zip(first_columns, third_columns):
print(first.text, third.text)
您可能会发现htql更容易做到这一点:
import htql
results=htql.query(html_data, "<table>1.<tr> {c1=<td>1:tx; c4=<td>4:tx } ");
导入htql
results=htql.query(html_数据,“1.{c1=1:tx;c4=4:tx}”);
使用美丽的汤:
感谢您的帮助看起来正是我所需要的,但我一直在第8行发现indexer:list index超出范围错误:table=soup.findAll('table')[0]@user3498833我测试了上面编写的代码。它不会给出错误
first_column = soup.select('table tr td:nth-of-type(1)')
fourth_column = soup.select('table tr td:nth-of-type(4)')