程序从网站获取标题列表。然后存储在变量(listOfjobs)中。我希望能够将该变量的内容(作业位置列表)写入现有文本文件,但它告诉我只接受字符串。如何在文本文件中将listOfJobs的值打印输出为纯文本?谢谢!
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()
答案 0 :(得分:0)
以字符串形式附加到文件列表:
'\n'.join(str(el) for el in listOfjobs)
最好使用上下文管理器进行文件处理:
with open('C:\\Users\\sk\\PycharmProjects\\test\\test_email.txt', 'a') as res:
res.write(''.join(str(el) for el in listOfjobs))
答案 1 :(得分:0)
每次运行代码时都需要打开a
才能追加,w
会覆盖:
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")