Reputation: 59
I need to write my Python output to csv. Because of my limited Python knowledge, I am unable to write a functional code. Currently with each loop of the code, I print a line. And I would like to write the lines to each row of a csv file. This is what I have so far (my loop actually runs over 100 cas #'s, I am only attaching 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)
Thanks in advance for any help!
Upvotes: 0
Views: 3278
Reputation: 11259
It looks like you don't understand the input to the csv writer. writerow
is expecting a sequence representing the columns. You are combining the 2 values into a catName
variable instead of passing them both to writerow
. What's happening is that writerow
is iterating over each item in the row, which in your case is a string, so it is splitting the string on each character.
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])
Upvotes: 3