如何创建一个在不同行中写入CSV的Python循环?

时间:2017-01-14 18:03:36

标签: python csv selenium

我是Python新手,我有一个脚本可以根据我想要的代码获取Yahoo Finance公司名称,行业和行业信息,并且所有内容都在不同的单元格中写入CSV,但是在一行中。如何让每个excel行显示我输入的每个股票代码的公司名称,行业和行业?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import csv

def get_all():
    results = []
    for x in tickers:
        try:
            website = "http://finance.yahoo.com/quote/{0}/profile?p={0}".format(x)
            driver = webdriver.Chrome()
            driver.get(website)
            wait = WebDriverWait(driver, 10)
            company = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="main-0-Quote-Proxy"]/section/div[2]/section/div/div[1]/div/h3')))
            results.append(company.text)
            wait = WebDriverWait(driver, 10)
            sector = wait.until(EC.visibility_of_element_located((By.XPATH, "//span[. = 'Sector']/following-sibling::strong")))
            results.append(sector.text)
            wait = WebDriverWait(driver, 10)
            industry = wait.until(EC.visibility_of_element_located((By.XPATH, "//span[. = 'Industry']/following-sibling::strong")))
            results.append(industry.text)
            driver.close()
        except Exception as e: 
            error_msg = "Error on {0}-{1}".format(x,e) 
            results.append(error_msg)
            driver.close()
    print(results)
    out = csv.writer(open("yahoo_companies.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
    out.writerow(results)

# Enter tickers below
tickers = ['COST', 'BBY']
get_all()

例如,我希望这个给我(每个分号将是一个不同的单元格):

第1行:Costco Wholesale Corporation;服务;折扣,综艺商店

第2行:Best Buy Co.,Inc。;服务;电子商店

第3行:等等......

现在我得到(All in Row 1):Costco Wholesale Corporation;服务;折扣,百货商店;百思买有限公司;服务;电子商店

1 个答案:

答案 0 :(得分:0)

在每行的末尾,您应该有一个换行符(\ n \ r),以便CSV编辑程序理解。

如果您将每一行添加到自己的列表中并将其添加到主“结果”列表中, writerows 将为每个元素添加行终止。

请参阅以下代码。

def get_all():
    results = []
    for x in tickers:
        # declare a new list to hold the values in each row
        newRow = []
        try:
            website = "http://finance.yahoo.com/quote/{0}/profile?p={0}".format(x)
            driver = webdriver.Chrome()
            driver.get(website)
            wait = WebDriverWait(driver, 10)
            company = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="main-0-Quote-Proxy"]/section/div[2]/section/div/div[1]/div/h3')))
            # appending to newRow list
            newRow.append(company.text)
            wait = WebDriverWait(driver, 10)
            sector = wait.until(EC.visibility_of_element_located((By.XPATH, "//span[. = 'Sector']/following-sibling::strong")))
            # appending to newRow list
            newRow.append(sector.text)
            wait = WebDriverWait(driver, 10)
            industry = wait.until(EC.visibility_of_element_located((By.XPATH, "//span[. = 'Industry']/following-sibling::strong")))
            # appending to newRow list
            newRow.append(industry.text)
            driver.close()
        except Exception as e: 
            error_msg = "Error on {0}-{1}".format(x,e) 
            # appending to newRow list
            newRow.append(error_msg)
            driver.close()
        # append the newRow list into 'results list'
        results.append(newRow)
    print(results)
    outFile = open("yahoo_companies.csv","w")
    out = csv.writer(outFile, delimiter=',',quoting=csv.QUOTE_ALL)
    # see the following line, its writerows (plural). different to your code.
    out.writerows(results)
    outFile.close()