Selenium Web驱动程序Python未循环

6yoyoihd  于 2022-12-23  发布在  Python
关注(0)|答案(1)|浏览(167)

我试图使用 selenium 点击多个链接,每次一个,以下载多个CSV文件,这里的问题是 selenium 使下载约几个CSV文件,但在循环中间停止工作,崩溃的浏览器accusin没有互联网和关闭驱动程序。我已经把chromedriver.exe在同一个文件夹中,并把路径,但它仍然不工作。

from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
import os
import re

new_directory = r"Z:\BI_Database_teste"
for document in os.listdir(new_directory):
    os.remove(os.path.join(new_directory, document))

url = 'myPersonalURL'

chrome_options = Options()
chrome_options.add_argument('--headless')
browser = webdriver.Chrome('chromedriver.exe', options=chrome_options)
params = {'behavior': 'allow', 'downloadPath': new_directory}
browser.execute_cdp_cmd('Page.setDownloadBehavior', params)
browser.get(url)

time.sleep(2)

input_email = browser.find_element(By.ID, 'email')
input_email.send_keys('myEmail')
input_password = browser.find_element(By.ID, 'password')
input_password.send_keys('myPassword')
input_password.submit()

input_question = browser.find_element(By.XPATH, '/html/body/div[2]/div[2]/form/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]').text
answer_field = browser.find_element(By.XPATH, '/html/body/div[2]/div[2]/form/table/tbody/tr[3]/td/table/tbody/tr[3]/td[2]/input')

if input_question == 'question':
    answer_field.send_keys('answer')
elif input_question == 'question':
    answer_field.send_keys('answer')
else:
    answer_field.send_keys('answer')

time.sleep(2)

answer_field.submit()
time.sleep(4)

links = browser.find_elements(By.LINK_TEXT, 'Export (CSV)')
links_len = len(links)
print(str(links_len) + ' BI Databases to Download')
list_count = 0

for link in range(list_count, links_len):
    time.sleep(2)
    links[list_count].click()
    list_count = list_count + 1
    print(str(list_count) + ' BI Databases downloaded')

browser.quit()

for file in os.listdir(new_directory):
    if file.startswith("PBI"):
        try:
            os.rename(os.path.join(new_directory, file), os.path.join(new_directory, re.sub('[0-9]', '', file)))
        except:
            pass

print('BI Databases Download Successfully!')```

Could someone help me to find out why the webdriver stops working in the middle of the loop?
t8e9dugd

t8e9dugd1#

如果您认为由于某种原因驱动程序没有正确加载,那么您可以在运行时从代码中下载webdriver,这可能会有所帮助。

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

chrome = webdriver.Chrome(ChromeDriverManager().install(), options=options)

如果没有更多的背景,这个问题就无法回答或重现。

相关问题