如何在 Selenium 中使用 Javascript 调用实现预期条件

How to implement Expected Conditions with Javascript calls in Selenium

我的 Python 下面的 Selenium 代码下载了里约热内卢的 shapefile。

import time, os
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select

options = webdriver.ChromeOptions()
preferences= {"download.default_directory": os.getcwd(), "directory_upgrade": True}
options.add_experimental_option("prefs", preferences)
#options.headless = True
options.add_experimental_option('excludeSwitches', ['enable-logging'])

url = "https://www.data.rio/datasets/limite-bairro/explore?location=-22.900784%2C-43.509500%2C10.83"

# Path of my WebDriver
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)

wait = WebDriverWait(driver, 10)


# to maximize the browser window
driver.maximize_window()

#get method to launch the URL
driver.get(url)

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#ember104"))).click()

time.sleep(10)

driver.execute_script('document.querySelector("#ember50 > div > div > div:nth-child(1) > div.download-panel > div > div:nth-child(8) > hub-download-card").shadowRoot.querySelector("calcite-card > div > calcite-dropdown > calcite-button").click()')

time.sleep(10)

driver.execute_script('document.querySelector("#ember50 > div > div > div:nth-child(1) > div.download-panel > div > div:nth-child(8) > hub-download-card").shadowRoot.querySelector("calcite-card > div > calcite-dropdown > calcite-dropdown-group > calcite-dropdown-item:nth-child(1)").click()')

虽然它有效,但我想知道如何在预期条件的框架内使用此语法 - 也就是说,我将如何使用

而不是必须告诉 Selenium 休眠十秒钟
wait.until()

与 Javascript 所以我不需要明确设置等待十秒的时间 - 毕竟,如果只用了不到十秒怎么办?知道我该怎么做吗?

您可以传递通过execute_script() as an argument to the expected_conditions of 返回的webelement并调用点击如下:

wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable(driver.execute_script("return document.querySelector("#ember50 > div > div > div:nth-child(1) > div.download-panel > div > div:nth-child(8) > hub-download-card").shadowRoot.querySelector("calcite-card > div > calcite-dropdown > calcite-button")"))).click()