【发布时间】:2023-03-25 01:31:01
【问题描述】:
我正在尝试解析 html 文件并将结果写入 csv 文件。 html文件是:
<table BORDER='1' CELLSPACING='0' CELLPADDING='0'>
<tr>
<td><small>15</small></td >
<td><small><small>Cat</small></small></td>
</tr>
<tr>
<td><small><small>16</small></small></td>
<td><small><small> </small></small></td>
</tr>
<tr>
<td><small>17</small></td >
<td><small><small>Dog</small></small></td>
</tr>
</table>
我的自动取款机代码是:
import csv
from BeautifulSoup import BeautifulSoup as bs
soup = bs (open("Animals.html"))
for i in soup.findAll('small'):
if " " in i.text:
i.string = '-'
print soup
f = csv.writer(open("Animals.csv", "a")) # Open the output file for writing before the loop
trs = soup.findAll('tr')
for tr in trs:
tds = tr.findAll("td")
try: #we are using "try" because the table is not well formatted. This allows the program to continue after encountering an error.
id = str(tds[0].get_text()) # This structure isolate the item by its column in the table and converts it into a string.
animal = str(tds[1].get_text())
except:
print "Bad tr string"
continue #This tells the computer to move on to the next item after it encounters an error
f.writerow([id, animal])
当我在替换 %nbsp; 后打印出汤的内容时,我得到:
<table BORDER='1' CELLSPACING='0' CELLPADDING='0'>
<tr>
<td><small>15</small></td >
<td><small></small><small>Cat</small></td >
</tr>
<tr>
<td><small><small>16</small></small></td >
<td><small></small><small>-</small></td >
</tr>
<tr>
<td><small>17</small></td >
<td><small></small><small>Dog</small></td >
</tr>
</table>
但是当我查看 .csv 文件时,它是空的。但是,如果我将代码更改为使用 BeautifulSoup 4,则无法替换 &nbsp;,但结果将保存到 .csv 文件中。我使用的另一个代码是:
import csv
from bs4 import BeautifulSoup as bs
soup = bs (open("Animals.html"))
f = csv.writer(open("Animals.csv", "w")) # Open the output file for writing before the loop
trs = soup.find_all('tr')
for tr in trs:
tds = tr.find_all("td")
try: #we are using "try" because the table is not well formatted. This allows the program to continue after encountering an error.
id = str(tds[0].get_text()) # This structure isolate the item by its column in the table and converts it into a string.
animal = str(tds[1].get_text())
except:
print "Bad tr string"
continue #This tells the computer to move on to the next item after it encounters an error
f.writerow([id, animal])
那个不会做我的原因是因为我希望将 &nbsp; 替换为 - 并且我无法让 (find_all()) 与 beautifulsoup 4 一起使用。
是什么导致信息被保存到 csv 文件中,我该如何修复它(和/或让它与 beautifulsoup 4 一起使用)?
【问题讨论】:
-
很抱歉只能提出一个替代解决方案,但是:如果文档的内容足够简单,为什么不尝试将
<small>元素中的&nbsp;替换为-by在使用 Beautiful Soup 处理内容之前使用正则表达式?
标签: python python-2.7 csv beautifulsoup