我是 python 新手,做了一个简单的爬虫,可以登录多个分析帐户并将一些数据打印到 CSV。我打印到 CSV 的格式是我使用以下代码创建的字典:
import csv
from collections import OrderedDict
import time
def save_file(website, visitors, links, sources):
date = time.strftime("%d/%m/%Y")
d = OrderedDict()
d['Title'] = website # website string
d['Date'] = date # date string
d['Vistors'] = visitors # integer
d['Links'] = links # dictionary of links - URL : Clicks
d['Sources'] = sources # dictionary of sources - Source: Clicks
path = os.path.expanduser('~/Desktop/Traffic Report.csv')
with open(path, 'a') as f:
writer = csv.DictWriter(f, d, delimiter=',')
writer.writerow(d)
当我使用此代码打印到 CSV 时,站点、日期和访问者单元格工作得很好。链接/源单元格(我使用 beautifulsoup 抓取的数据)充满了额外的引号和字符,如下所示。
{"['www.example1.com/']": '1', "['www.example2.com']": '1', "['www.example3.com']": '1', "['www.example4.com/']": '3', "['www.example5.com/']": '1'}
{"['Links']": '2', "['Social media']": '5', "['Direct']": '2', "['Searches']": '1'}
有没有办法删除许多这些字符并打印到 csv 为: www.example1.com : 1, www.example2.com : 1, www.example3.com : 1 ...
任何帮助将不胜感激!