在 python 中使用循环抓取时如何将每次迭代的输出导出到 csv

How to export to csv the output of every iteration when scraping with a loop in python

我对 Python 很陌生。我正在尝试抓取一个网站并为此创建了一个小代码:

select = Select(character.find_element_by_id('character-template-choice'))
options = select.options
for index in range(0, len(options) - 0):
    select.select_by_index(index)
    option1 = character.find_elements_by_class_name('pc-stat-value')
    power = []
    for c in option1:
        power.append("Power:" + c.text)
    option2 = character.find_elements_by_class_name(
        'unit-stat-group-stat-label')
    skills = []
    for a in option2:
        skills.append(a.text)
    option3 = character.find_elements_by_class_name(
        'unit-stat-group-stat-value')
    values = []
    for b in option3:
        values.append(b.text)
 test = [power, skills, values]
 print(test)
 df = pd.DataFrame(test).T
 df.to_csv('test2.csv', index=False, header=False)

我遇到的问题是,当我尝试将列表的“测试”列表导出到 csv 时,我只得到最后一次迭代。我想获取每次迭代的数据,但我不知道该怎么做。有人可以帮助我吗?

谢谢

您将需要在每次迭代时附加这三个列表,以最终得到全部:

select = Select(character.find_element_by_id('character-template-choice'))
options = select.options
test = []  # Create empty list
for index in range(0, len(options) - 0):
    select.select_by_index(index)
    option1 = character.find_elements_by_class_name('pc-stat-value')
    power = []
    for c in option1:
        power.append("Power:" + c.text)
    option2 = character.find_elements_by_class_name(
        'unit-stat-group-stat-label')
    skills = []
    for a in option2:
        skills.append(a.text)
    option3 = character.find_elements_by_class_name(
        'unit-stat-group-stat-value')
    values = []
    for b in option3:
        values.append(b.text)
    test.append([power, skills, values])  # Add a list of lists to your test

print(test)
df = pd.DataFrame(test).T
df.to_csv('test2.csv', index=False, header=False)

这将为您提供一个列表 test,在一个列表中包含 power, skills, values 用于迭代。