简体   繁体   English

从嵌套循环写入 output 到 csv ?

[英]Write output to csv from nested loop?

I have several loops within a larger loop, and I need the csv file to be written to twice:我在一个较大的循环中有几个循环,我需要将 csv 文件写入两次:

UPDATED, more detailed example更新,更详细的例子

with open("file.csv", "w", encoding="utf-8", newline="") as file:
    writer = csv.writer(file)
    while True:
        try:
            element = driver.find_element_by_xpath(xpath)
            if element.is_displayed():
                nextbtn=driver.find_element_by_xpath(xpath).click()
                object=driver.find_element_by_xpath(xpath)
                writer.writerows(object)
        except NoSuchElementException:
            urls=driver.find_elements_by_xpath(xpath)
            urls= [url.get_attribute('href') for url in urls]

            for url in urls:
                driver.get(url)
                object = driver.find_element_by_xpath(xpath)
                writer.writerows(object)

Essentially what the code is doing is testing to check if an element is present.本质上,代码所做的是测试以检查元素是否存在。 If the element is present, the next button is clicked.如果元素存在,则单击下一个按钮。 Once the next button is clicked, a specific element, object , is scraped and written to csv.单击下一个按钮后,将抓取特定元素object并将其写入 csv。

If the certain element is not present, the code then collects a list of urls, and for each url, it scrapes the element object and prints it to csv.如果某个元素不存在,则代码会收集一个 url 列表,并且对于每个 url,它会抓取元素object并将其打印到 csv。

Regardless of which page is navigated to, I want the object element.无论导航到哪个页面,我都想要 object 元素。 However, the problem lies in writing to csv, as the results from try are not being written to the csv.但是,问题在于写入 csv,因为try的结果没有写入 csv。 Although the location of object is the same for both pages, the value of object is different, depending on the page.虽然object的位置对于两个页面是相同的,但object的值是不同的,具体取决于页面。

How would I rewrite this code such that both results are written in the same.csv?我将如何重写此代码以使两个结果都写在相同的 csv 中?

For anyone else that runs into the same issue, the problem was NOT the syntax writing to.csv.对于遇到相同问题的其他任何人,问题不是写入到.csv 的语法。 To write to a.csv in a nested loop, the syntax I posted above is correct.要在嵌套循环中写入 a.csv,我在上面发布的语法是正确的。

The issue in this case was that the element object I was trying to find in the try loop was not being found, and was therefore writing empty rows, whereas the object was being found in the except loop.在这种情况下,问题是没有找到我试图在try循环中找到的元素object ,因此写入了空行,而在except循环中找到了 object。 I used an if/else statement within the try to write a cell "element not found" to csv.我在try将单元格“找不到元素”写入 csv 时使用了 if/else 语句。 Alternatively, you could just leave it blank.或者,您可以将其留空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM