简体   繁体   English

while循环-将输出发送到csv文件

[英]while loop - sending output to csv file

This goes to a URL from the CSV file , then scrolls down. 这将从CSV文件转到URL,然后向下滚动。 I'm trying to grab the company URLs off of the page. 我正在尝试从页面中获取公司URL。 I can't seem to get it to work. 我似乎无法正常工作。 Now if I use just one stand alone URL without pulling it from the CSV, it will print to powershell. 现在,如果我仅使用一个独立的URL而不将其从CSV中提取,它将打印到powershell中。 Still can't get it to write to CSV. 仍然无法将其写入CSV。

Here is a couple of URLs that I'm working with: 这是我正在使用的几个URL:

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

The thought I had was that it has to be a loop within a loop. 我本来以为它必须是一个循环中的一个循环。 Or, it could be if , elif . 或者, ifelif I'm not really sure at this point. 我现在还不确定。 Any and all suggestions would be appreciated. 任何和所有建议,将不胜感激。

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'))

Instead of opening the file in write mode open('file','w') open it in append mode open('file','a') 与其以写模式open('file','w')打开open('file','w')是以附加模式open('file','a')

Found in how to add lines to existing file using python 发现如何使用python向现有文件添加行

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

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