1

Program gets a list of titles from a website. Then stored in a variable (listOfjobs). I want to be able to write the contents of that variable (a list of job positions) appending it to an existing text file, but it tells me that only strings are accepted. How can I include the printout of the values of listOfJobs as plain text in a text file? Thanks!

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://jobs.theguardian.com/searchjobs/?LocationId=1500&keywords=personal+assistant&radialtown=London+(Central)%2c+London+(Greater)&countrycode=GB')

elem = browser.find_elements_by_class_name('lister__header')

for el in elem:                 
   listOfJobs = print(el.text)
    print(listOfJobs)


import os
helloFile = open('C:\\Users\\sk\\PycharmProjects\\test\\test_email.txt', 'w')
helloFile.write(websiteText)
helloFile.close()
skeitel
  • 271
  • 2
  • 6
  • 17

2 Answers2

0

Append to file list as string:

'\n'.join(str(el) for el in listOfjobs)

And better to use context manager for file processing:

with open('C:\\Users\\sk\\PycharmProjects\\test\\test_email.txt', 'a') as res:
    res.write(''.join(str(el) for el in listOfjobs))
xiº
  • 4,605
  • 3
  • 28
  • 39
0

You need to open with a to append each time you run the code, w overwrites:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://jobs.theguardian.com/searchjobs/?LocationId=1500&keywords=personal+assistant&radialtown=London+(Central)%2c+London+(Greater)&countrycode=GB')

elem = browser.find_elements_by_class_name('lister__header')


with open('C:\\Users\\sk\\PycharmProjects\\test\\test_email.txt', "a") as f:
    for el in elem:                 
       f.write(el.text+"\n")
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    This worked. THANK YOU very much for posting whole code, helps me learn. I see you saved lines in your code by using "with" but I never learned about this command on basic programming course. Anyone knows the best resource to learn more about how to use "with" command, or how to use less lines like @Padraic Cunningham did? – skeitel Oct 05 '15 at 09:32
  • @skeitel, no worries, `with` will automatically close your file for you, https://www.python.org/dev/peps/pep-0343/, if you want a tutorial from the basic ups this is a nice resource http://anandology.com/python-practice-book/getting-started.html – Padraic Cunningham Oct 05 '15 at 09:37
  • 1
    Thanks PC. I found this, which seemed shorter and clearer: http://effbot.org/zone/python-with-statement.htm – skeitel Oct 05 '15 at 10:15