如何使用 BeautifulSoup 从 html 文件中提取 table 数据?
How to extract table data from html file with BeautifulSoup?
我正在尝试清理一些数据,我必须准备好将其移入数据库。我不是职业程序员,所以这对我来说是全新的。我一直在搜索该站点,试图找到要尝试的示例代码。我找到了这个讨论,正如你所看到的,我试图让我的情况适应它:
How to extract html table by using Beautifulsoup
<html>
<head>
<title>This the title.</title>
</head>
<body>
<center>
<br />
<br />
<h2>Test Case 1</h2>
</center>
<table align="center" border="1" cellpadding="0" cellspacing="1" width="650">
<tr>
<td>
<font size="1"> Cell Title 1</font>
<br /> </td>
<td>
<font size="1"> Cell Title 2</font>
<br /> </td>
<td>
<font size="1"> Cell Title 3</font>
<br />
<font size="2">Value</font></td>
<td>
<font size="1"> Cell Title4</font>
<br />
<font size="2">Value</font></td>
这里是错误:
Traceback (most recent call last): File "ExtractTest2.py", line 35, in
print soup.find("td", {"size":"2"}).find_parent('table')
AttributeError: 'NoneType' object has no attribute 'find_parent'
我的最终目标是打印出来
Cell Title X : Value
如果有一个值,因为会有一个单元格标题。
我哪里错了?
soup.find("td", {"size":"2"})
主要问题在这里 - HTML 中的 td
元素没有 size
属性。
相反,检查 font
元素上的 size
。示例代码:
for title in soup.find_all("font", {"size": "1"}):
value = title.find_next_sibling("font", {"size": "2"})
print title.text, " | ", value.text if value else "No Value"
打印:
Cell Title 1 | No Value
Cell Title 2 | No Value
Cell Title 3 | Value
Cell Title4 | Value
我正在尝试清理一些数据,我必须准备好将其移入数据库。我不是职业程序员,所以这对我来说是全新的。我一直在搜索该站点,试图找到要尝试的示例代码。我找到了这个讨论,正如你所看到的,我试图让我的情况适应它: How to extract html table by using Beautifulsoup
<html>
<head>
<title>This the title.</title>
</head>
<body>
<center>
<br />
<br />
<h2>Test Case 1</h2>
</center>
<table align="center" border="1" cellpadding="0" cellspacing="1" width="650">
<tr>
<td>
<font size="1"> Cell Title 1</font>
<br /> </td>
<td>
<font size="1"> Cell Title 2</font>
<br /> </td>
<td>
<font size="1"> Cell Title 3</font>
<br />
<font size="2">Value</font></td>
<td>
<font size="1"> Cell Title4</font>
<br />
<font size="2">Value</font></td>
这里是错误:
Traceback (most recent call last): File "ExtractTest2.py", line 35, in print soup.find("td", {"size":"2"}).find_parent('table') AttributeError: 'NoneType' object has no attribute 'find_parent'
我的最终目标是打印出来
Cell Title X : Value
如果有一个值,因为会有一个单元格标题。
我哪里错了?
soup.find("td", {"size":"2"})
主要问题在这里 - HTML 中的 td
元素没有 size
属性。
相反,检查 font
元素上的 size
。示例代码:
for title in soup.find_all("font", {"size": "1"}):
value = title.find_next_sibling("font", {"size": "2"})
print title.text, " | ", value.text if value else "No Value"
打印:
Cell Title 1 | No Value
Cell Title 2 | No Value
Cell Title 3 | Value
Cell Title4 | Value