首页 > 解决方案 > 如何将多字标题绑定到它的值从 csv 作为字典

问题描述

我正在从 HTML 表中抓取数据,并希望将多字标题绑定在一起作为正确值的字典键。我应该如何绑定正确的标题?最后我应该如何删除不需要的标题?

with open(filename, 'w') as f:
    for span in all_spans:
        num_page_items = len(all_spans)
        f.write(span.text)
driver.close()


with open(filename) as csvfile:  # Reading csv file 
    csvreader = csv.DictReader(csvfile, delimiter=' ')
    mydict = {}
    for col in csvreader:
        print(col)

我希望输出看起来像 -

代码{'AIZ', ('股份': 1520), ('购买价格': 106.31), ('市场价格': 111.59), ('总价值': 169,616.80), ('收益/亏损': 8,025.60) , ('收益/损失%': 0.050%)}

如果我使用 csv.DictReader 我得到 -

OrderedDict([('Symbol', 'AIZ'), ('Shares', '1520'), ('Purchase', '$106.31'), ('Price', '$8,025.60'), ('Market', '$169,616.80 '), ('Total', '0.050%'), ('Value', 'Buy'), ('Gain/Loss', 'Sell'), ('%', None), ('Actions', None )])

如果我会使用 csv.reader 我会得到 -

['AIZ', '1520', '$106.31', '$111.59', '$169,616.80', '$8,025.60', '0.050%', '买入', '|', '卖出']

输出文件

标签: python-3.xcsvselenium-webdriverweb-scraping

解决方案


推荐阅读