如何在python中将对象列表存储为CSV?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (256)

我正在编写一个程序,它可以抓取一个网站,并从一个表中提取名称和链接。我将每个名称和相应的链接存储在一个对象中,并通过运行for循环将其附加到对象列表中。我想将这个列表保存为一个CSV文件,但是由于它将整个对象转换为str,所以无法使用filewriter来实现,这是我的代码:

from selenium import webdriver
from bs4 import BeautifulSoup

class Player():
    def __init__(self):
        self.name = ""
        self.link = ""

player_list = []

driver = webdriver.PhantomJS(executable_path = r'C:\Users\sarim\Desktop\Scraper\phantomjs.exe')
driver.get('https://dak.gg/ranks/na/solo-fpp/rating')
pause = 0
lastHeight = driver.execute_script("return document.body.scrollHeight")
while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(pause)
    newHeight = driver.execute_script("return document.body.scrollHeight")
    if newHeight == lastHeight:
        break
    lastHeight = newHeight

html_doc = driver.page_source
soup = BeautifulSoup(html_doc, 'lxml')

players = soup.find('table', class_ = 'list rating')
player_names = players.find_all('td', class_ = 'nick')

add_link = "https://dak.gg"

for i in player_names[0:3]:
    newPlay = Player()
    n = i.find('a')
    l = add_link + n['href']
    newPlay.link = l
    newPlay.name = n.text.strip()
    #print newPlay.name
    #print newPlay.link
    player_list.append(newPlay)

#print players_names[1]
driver.quit()
提问于
用户回答回答于

试试这个方法:

import csv
with open('data.csv', 'w',) as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Name', 'Link'])
    for player in player_list:
        writer.writerow([player.name, player.link])

扫码关注云+社区

领取腾讯云代金券