【问题标题】:while loop - sending output to csv filewhile 循环 - 将输出发送到 csv 文件
【发布时间】:2019-04-01 10:55:51
【问题描述】:

这会转到 CSV 文件中的 URL,然后向下滚动。我正在尝试从页面中获取公司 URL。我似乎无法让它工作。现在,如果我只使用一个独立的 URL 而不从 CSV 中提取它,它将打印到 powershell。仍然无法将其写入 CSV。

这是我正在使用的几个 URL:

https://www.facebook.com/search/pages/?q=Los%20Angeles%20remodeling
https://www.facebook.com/search/pages/?q=Boston%20remodeling

我的想法是它必须是循环中的循环。或者,它可能是ifelif。我现在还不确定。任何和所有建议将不胜感激。

import time
from selenium import webdriver
from bs4 import BeautifulSoup as bs
import csv
import requests
from selenium.webdriver.support.ui import WebDriverWait


driver = webdriver.Chrome()
elems = driver.find_elements_by_class_name('_32mo')


chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)


driver.get('https://www.facebook.com')
username = driver.find_element_by_id("email")
password = driver.find_element_by_id("pass")
username.send_keys("*****")
password.send_keys("******")
driver.find_element_by_id('loginbutton').click()
time.sleep(2)



with open('fb_urls.csv') as f_input, open('fb_profile_urls.csv', 'w', newline=)  as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)
    for url in csv_input:
        driver.get(url[0])
        time.sleep(5)
        lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
        match=False
        while(match==False):
            lastCount = lenOfPage
            time.sleep(1)
            lenOfPage = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
            if lastCount==lenOfPage:
                match=True
                for elem in elems:
                    csv_output.(driver.find_elements_by_tag_name('href'))

【问题讨论】:

  • 我不确定我是否理解您的问题,所以大胆猜测:open('fb_profile_urls.csv', 'w', newline=) 将在您每次运行此脚本时擦除文件
  • 看,我也是这么想的。但是,通过研究,这是我在 SO 的解决方案中发现的。
  • 不,它肯定每次运行脚本时都会擦除文件

标签: python loops csv


【解决方案1】:

不是以写入模式打开文件open('file','w')以附加模式打开文件open('file','a')

发现于how to add lines to existing file using python

【讨论】:

  • 这几乎是滑稽的,我只是从表面上看它不会。我知道更好。即使在这样做之后它也不起作用。运行后只是一张白纸
  • 愚蠢的问题,您是否在执行'w' 和执行'a' 之前使用更多数据重新填充文件?当我运行fname = 'testfile1.txt' with open(fname,'w') as f: f.write('Some Junk') 文件包含Some Junk 然后我运行with open(fname,'a') as f: f.writelines('\nmorejunk') 它包含Some Junk morejunk
  • 我明白你在说什么。如果我做你刚才做的,它工作正常。它必须与循环有关。我不太确定是我在哪里命名为“elems”,还是在最后写了一个“for”循环以将其打印到文件中。这有意义吗?
  • 它在哪里写 csv_output.(driver... 它没有;看起来你不是在调用 writerow() 函数,因此没有给它写任何东西
  • 试过了......它也不起作用。 T.T 在过去的几个小时里,我一直在绞尽脑汁思考如何让它发挥作用。我想我已经准备好认输了。
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2022-11-28
  • 1970-01-01
  • 2020-02-10
  • 2020-10-25
  • 1970-01-01
  • 2013-09-28
相关资源
最近更新 更多