【发布时间】:2017-08-13 07:28:00
【问题描述】:
我正在尝试将列表的内容添加到 CSV 文件。首先,我使用 BeautifulSoup 抓取网页以获取第一列的内容。然后我再次使用 BeautifulSoup 来抓取其余列的内容。我的代码是:
# Content first column
playerName = soup.find('div', class_='font-16 fh-red').text
# Content second column
playerStats = []
for stat in soup.find_all('span', class_='player-stat-value'):
playerStats.append(stat.text)
# Write name and stats to CSV file
with open('players.csv', 'a') as csvfile:
dataWriter = csv.writer(csvfile)
dataWriter.writerow([playerName, playerStats])
playerName 已正确写入 CSV 文件。但是,整个 playerStats 列表被写入第二列。 我希望将单个列表元素写入 CSV 文件的第二、第三、第四等列。我该怎么做?
只是为了澄清一下:我以“a”模式打开文件,因为我之前在 Python 代码中编写了 CSV 文件的标题。
【问题讨论】:
标签: python python-3.x csv beautifulsoup