Manoj Kengudelu
Manoj Kengudelu

Reputation: 665

Unable to write extracted text as individual rows in csv

This may be considered as second part of question Finding an element within an element using Selenium Webdriver.

What Im doing here is, after extracting each text from the table, writing it into csv file

Here is the code:

from selenium import webdriver
import os
import csv

chromeDriver = "/home/manoj/workspace2/RedTools/test/chromedriver"
os.environ["webdriver.chrome.driver"] = chromeDriver
driver = webdriver.Chrome(chromeDriver)
driver.get("https://www.betfair.com/exchange/football/coupon?id=2")
list2 = driver.find_elements_by_xpath('//*[@data-sportid="1"]')

couponlist = []
finallist = []
for game in list2[1:]:
    coup = game.find_element_by_css_selector('span.home-team').text
    print(coup)
    couponlist.append(coup)
print(couponlist)
print('its done')


outfile = open("./footballcoupons.csv", "wb")
writer = csv.writer(outfile)
writer.writerow(["Games"])
writer.writerows(couponlist)

Results of 3 print statements:

Santos Laguna
CSMS Iasi
AGF
Besiktas
Malmo FF
Sirius
FCSB
Eibar
Newcastle
Pescara

[u'Santos Laguna', u'CSMS Iasi', u'AGF', u'Besiktas', u'Malmo FF', u'Sirius', u'FCSB', u'Eibar', u'Newcastle', u'Pescara']

its done

Now, You can notice the code where i write these values into csv. But I end up writing it weirdly into csv. please see the snapshot. Can someone help me to fix this please?enter image description here

Upvotes: 0

Views: 55

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

According to the documentation, writerows takes as parameter a list of rows, and

A row must be an iterable of strings or numbers for Writer objects

You are passing a list of strings, so writerows iterates over your strings, making a row out of each character.

You could use a loop:

for team in couponlist:
    writer.writerow([team])

or turn your list into a list of lists, then use writerows :

couponlist = [[team] for team in couponlist]
writer.writerows(couponlist)

But anyway, there's no need to use csv if you only have one column...

Upvotes: 3

Related Questions