【发布时间】:2020-02-26 05:13:23
【问题描述】:
我正在尝试从该网站 (https://blog.prepscholar.com/act-to-sat-conversion) 解析第二个表并将其输出为 CSV 文件。我无法将输出写入 CSV,因此我尝试为每一行创建字符串,然后将其列出以写入 CSV,但我失败了。你可以帮帮我吗?非常感谢!
这是我目前的代码:
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
tpage1 = 'https://blog.prepscholar.com/act-to-sat-conversion'
hpage = urlopen(tpage1)
bs = BeautifulSoup(hpage, 'html.parser')
for h1 in bs.find_all('h1'):
print(h1.get_text())
table = bs.find_all('table')[1]
rows = table.find_all('tr')
headers = table.find_all('th')
rownum = 0
for row in rows:
rownum += 1
cellnum = 0
new_row = ''
for cell in row.find_all(['td','th']):
cellnum += 1
print(rownum, cellnum, cell.get_text())
这段代码给了我一个输出(下面是一个sn-p)
SAT / ACT Prep Online Guides and Tips
1 1 ACT Composite Score
1 2 Estimated SAT Composite
1 3 Estimated SAT Composite Range
2 1 36
2 2 2390
2 3 2320-2400
3 1 35
3 2 2260
3 3 2320-2310
4 1 34
4 2 2170
4 3 2140-2220
如何修改它以输出到 CSV?
【问题讨论】:
-
csw_writer.writerow([rownum, cellnum, cell.get_text()])? -
什么是“失败”?如果您收到错误消息,那么您应该将其显示为有问题的(不是在评论中)作为文本(不是图像)。不要期望我们会运行代码来查看错误消息 - 并且代码可以在我们的计算机上正确运行。
-
试试
pandas-all_tables = pandas.read_html('https://blog.prepscholar.com/act-to-sat-conversion')andall_tables[0].to_csv("output1.csv")andall_tables[1].to_csv("output2.csv") -
也许你应该将一行中的单元格保留在单个列表中,而不是字符串中,然后再写这个列表。
标签: python csv parsing beautifulsoup datatable