Selenium Python无法在for循环中正确编写csv

时间:2017-03-20 04:22:05

标签: python selenium

我正在尝试在excel电子表格中的for循环中写入数据,我最终希望得到如下代码:

f.write(ln.text + "," + av.text + "\n")

然而,它不会按我想要的方式工作,所以我必须这样做,这里的代码

Main.py

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import csv
from selenium.webdriver.support.ui import WebDriverWait
import unittest





class Test():
    # filename = "list.csv"
    # f = open(filename,"w")
    # headers = "listing name, aval \n"

    # f.write(headers)

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get("https://orlando.craigslist.org/search/apa?s=100")
        self.filename = "list.csv"
        self.f = open(self.filename,"w")
        self.headers = "listing name, aval \n"
        self.f.write(self.headers)

    def task(self):
        driver = self.driver
        filename = self.filename
        f = self.f
        headers = self.headers
        ln = driver.find_elements_by_xpath('//*[@id="sortable-results"]/ul/li/p/a')
        size = len(driver.find_elements_by_xpath('//*[@id="sortable-results"]/ul/li/p/a'))
        for i in range(0, size):
            ln = driver.find_elements_by_xpath('//*[@id="sortable-results"]/ul/li/p/a')
            ln = ln[i]
            f.write(ln.text + ",")
            self.getLn(ln)
            ln = ln.click()
            av = driver.find_element_by_xpath('/html/body/section/section/section/div[1]/p[1]/span[2]')
            f.write(av.txt + "\n")
            self.getAv(av)

            back = driver.find_element_by_xpath('/html/body/section/header/nav/ul/li[3]/p/a').click()
            if i == 5:
                f.close()
                break





    def getLn(self,ln):
        driver = self.driver
        ln = ln
        if ln:
            print (ln.text)
        else:
            print ("No listing name")



    def getAv(self,av):
        driver = self.driver
        if av:
            print (av.text)
        else:
            print ("No listing name")


    def initialize():
        return Test

    def teardown(self):
        self.driver.quit()



run = Test()
run.setUp()
tas = run.task()
run.teardown()






if __name__ == '__main__':
    unittest.main()

它有效,但它不会像我想要的那样在csv上导出。

我最终希望将输出放在同一行中,如下所示:

f.write(ln.text +“,”+ av.text +“\ n”)

我该怎么做?

1 个答案:

答案 0 :(得分:1)

我强烈建议您将代码带到Code Review,因为它有严重的风格问题,但这应该可以解决您当前的问题:

for i in range(0, size):
    ln = driver.find_elements_by_xpath('//*[@id="sortable-results"]/ul/li/p/a')
    ln = ln[i]
    ln_text = ln.text  # copy the text for usage later
    self.getLn(ln)
    ln.click()
    av = driver.find_element_by_xpath('/html/body/section/section/section/div[1]/p[1]/span[2]')
    f.write(ln_text + ',' + av.text + "\n")  # write both parts
    self.getAv(av)

    back = driver.find_element_by_xpath('/html/body/section/header/nav/ul/li[3]/p/a').click()
    if i == 5:
        f.close()
        break