从 html 中提取表格数据并保存为文本文件

Extract tabular data from a html and save as text file

我想从 html 中提取表格数据并另存为 text file

import urllib2, numpy as np, pandas as pd
fo = 'fo.txt'
url = 'https://coinmarketcap.com/currencies/bitcoin/historical-data/'
html = urllib2.urlopen(url).read()
rows = pd.read_html(html)
print type(rows)
print rows

for row in rows:
    this_row = "|".join([str(td) for td in row])
    fo.write(this_row + "\n")

但出现错误:

Traceback (most recent call last):
    fo.write(this_row + "\n")
AttributeError: 'str' object has no attribute 'write'

文本文件中生成的表格数据看起来与原始文件中的一样link: https://coinmarketcap.com/currencies/bitcoin/historical-data/

任何帮助,请!

如果你想写入一个文本文件,你需要一个文件对象。在您的源代码中,fo 对象是一个 string

在python中你可以打开一个文件这样写:

with open(fo,'w') as text_file:
    for row in rows:
        this_row = row
        text_file.write(this_row + "\n")