python为循环结果写入csv

时间:2014-07-09 18:45:33

标签: python csv

我需要将我的Python输出写入csv。由于我有限的Python知识,我无法编写功能代码。 目前,每个循环的代码,我打印一行。我想将行写入csv文件的每一行。这是我到目前为止(我的循环实际上运行超过100个cas#,我只附加2)。

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import csv

url = "http://www.sigmaaldrich.com/united-states.html"
cas = ['50893-53-3','2094-98-6']

with open('name.csv', 'w') as file:
    writer = csv.writer(file, delimiter = '\t', lineterminator = '\n',)
    for i in cas:
        driver = webdriver.Firefox()
        driver.get(url)

        inputElement = driver.find_element_by_name("Query")
        inputElement.send_keys(i)
        inputElement.submit()

        name = driver.find_element_by_css_selector("h2.name").text
        purity = driver.find_element_by_css_selector("li.applicationValue a").text
        catName = u" ".join((name, purity)).encode("utf-8")
        catName = catName.replace("(Sigma-Aldrich)" , "")
        catName = catName.replace("(Aldrich)" , "")
        catName = catName.replace("(Sigma)", "")
        print(catName)

        driver.quit()

        row = catName
        writer.writerow(row)

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

看起来你不了解csv编写器的输入。 writerow期待表示列的序列。您将2个值组合到catName变量中,而不是将它们都传递给writerow。发生了什么writerow正在迭代行中的每个项目,在您的情况下是一个字符串,因此它会在每个字符上拆分字符串。

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import csv

url = "http://www.sigmaaldrich.com/united-states.html"
cas = ['50893-53-3','2094-98-6']

with open('name.csv', 'w') as file:
    writer = csv.writer(file, delimiter = '\t', lineterminator = '\n',)
    for i in cas:
        driver = webdriver.Firefox()
        driver.get(url)

        inputElement = driver.find_element_by_name("Query")
        inputElement.send_keys(i)
        inputElement.submit()

        name = driver.find_element_by_css_selector("h2.name").text.encode("utf-8")
        purity = driver.find_element_by_css_selector("li.applicationValue a").text.encode('utf-8')
        purity = purity.replace("(Sigma-Aldrich)" , "")
        purity = purity.replace("(Aldrich)" , "")
        purity = purity.replace("(Sigma)", "")
        print [name, purity]

        driver.quit()

        writer.writerow([name, purity])