【发布时间】:2017-11-22 18:15:14
【问题描述】:
我正在尝试解析 HTML 表格并将其写入 CSV。我的代码有效,但它为表中具有值的每个单元格返回b'<value>',为表中为空的每个单元格返回b''。有谁知道为什么会这样?
不幸的是,有问题的 URL 无法通过公共互联网访问,但这是我的代码供我在没有它的情况下进行审查:
from bs4 import BeautifulSoup
import urllib
import csv
import time
url = <not accessible over public internet>
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, "html.parser")
table = soup.select_one("table")
headers = [th.text.encode("utf-8") for th in table.select("tr th")]
with open("test_" + time.strftime("%Y%m%d_%H%M%S") + ".csv", "w") as f:
wr = csv.writer(f)
wr.writerow(headers)
wr.writerows([[td.text.encode("utf-8") for td in row.find_all("td")] for row in table.select("tr + tr")])
最后,这是我正在谈论的输出的屏幕截图示例。 (原谅删掉敏感内容造成的丑陋。)
【问题讨论】:
标签: python html csv parsing beautifulsoup