2

我正在尝试将第二个值写入text_entries文件,但我不想在我的 .csv 中包含第一个值——例如 index2、index3 等。

如何在不向 CSV 输出添加索引标题的情况下写入新行?下面的代码:

import csv
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://www.example.se/list')

def get_elements_by_xpath1(driver, xpath):
        return [entry.text for entry in driver.find_elements_by_xpath(xpath)]

text_entries = [
    ("index2", "//div[@class='apartment-fact' and contains(span, '')][1]"),
    ("index3", "//div[@class='apartment-fact' and contains(span, '')][2]"),
    ("index4", "//div[@class='apartment-fact' and contains(span, '')][3]"),
    ("index5", "//div[@class='apartment-fact' and contains(span, '')][4]")]

with open('output.csv', 'ab') as fd:
    csv_output = csv.writer(fd)
    csv_output.writerow([name for name, xpath in text_entries])
    entries = []
    for name, xpath in text_entries:
        entries.append(get_elements_by_xpath1(driver, xpath))
    csv_output.writerows(zip(*entries))
4

1 回答 1

1

这似乎做你想做的事:


import csv

def get_elements_by_xpath1(driver, xpath):
    return [entry.text for entry in driver.find_elements_by_xpath(xpath)]

text_entries = [
    ("index2", "//div[@class='apartment-fact' and contains(span, '')][1]"),
    ("index3", "//div[@class='apartment-fact' and contains(span, '')][2]"),
    ("index4", "//div[@class='apartment-fact' and contains(span, '')][3]"),
    ("index5", "//div[@class='apartment-fact' and contains(span, '')][4]")]

with open('output.csv', 'a') as fd:
    csv_output = csv.writer(fd)
    for _, xpath in text_entries:
        csv_output.writerow([xpath] + get_elements_by_xpath1(driver, xpath))
于 2019-10-15T20:57:01.440 回答