我正在使用 selenium 单击网站并自动下载,目前我对如何让 selenium 切换到选择下载按钮时创建的弹出窗口感到困惑。简而言之,我想与弹出窗口进行交互,但不熟悉执行此操作的函数/语法或过程。谢谢!
如果找到解决方案,我会更新!
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
import time
chrome = 'path'
url = "url"
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.get(url)
driver.maximize_window()
print("Press CTRL+C to stop program. Close Chrome Browser and stop Chrome Processes in Task Manager")
iframe = '//*[@id="viz"]/iframe'
xpath1 = '/html/body/div[2]/div[2]/div[1]/div[2]/div[2]/div[5]/button'
xpath2 = '/html/body/div[6]/div/div/div/div[2]/div'
xpath3 = ''
try:
iframe = WebDriverWait(driver, 15).until(
EC.presence_of_element_located((By.XPATH, iframe))
)
driver.switch_to.frame(iframe)
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, xpath1))
)
element.click()
element2 = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, xpath2))
)
element2.click()
except TimeoutException:
print("Element not found. Retrying...")
time.sleep(10)
正如评论中提到的“fiji”,使用带有
move_to_element()
的操作链提供了一种更可靠的与元素交互的方式,特别是在简单点击可能不够的情况下。
根据处理弹出窗口的具体要求调整 try
块内的操作。
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
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.common.exceptions import TimeoutException
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
chrome = 'path'
url = "url"
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.get(url)
driver.maximize_window()
print("Press CTRL+C to stop program. Close Chrome Browser and stop Chrome Processes in Task Manager")
iframe = '//*[@id="viz"]/iframe'
xpath1 = '/html/body/div[2]/div[2]/div[1]/div[2]/div[2]/div[5]/button'
xpath2 = '/html/body/div[6]/div/div/div/div[2]/div'
xpath3 = ''
try:
iframe = WebDriverWait(driver, 15).until(
EC.presence_of_element_located((By.XPATH, iframe))
)
driver.switch_to.frame(iframe)
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, xpath1))
)
# Using Action Chains to click the element
actions = ActionChains(driver)
actions.move_to_element(element).click().perform()
# Now you can handle the pop-up window,
# Perform actions on the pop-up window as needed
finally:
pass
# Close the pop-up window
driver.close()
# Switch back to the main window
driver.switch_to.window(driver.window_handles[0])