0

我对 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 时,我只得到最后一次迭代。我想获取每次迭代的数据,但我不知道该怎么做。有人能帮我吗?

谢谢

4

1 回答 1

0

您需要在每次迭代时附加这三个列表才能最终获得所有内容:

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一个用于迭代的列表。

于 2020-11-26T17:35:01.287 回答