Issue
I am attempting to write the 2nd value in text_entries
to a file, but I do not want to include the first value in my .csv -- such as index2, index3, etc.
How can I write new rows without adding index headers to my CSV output? Code below:
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))
Solution
This seems to do what you want:
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))
Answered By - Chris W.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.