在 driver.get(url) 完全加载之前如何在 selenium 中执行键盘操作?

问题描述 投票:0回答:1

我想在 driver.get(url) 启动后按 ENTER 。因为除非按 ENTER 键,否则页面不会加载。无论我尝试什么方法,都只会在 URL 加载后执行键盘操作。

我尝试过机器人类和动作类,但它不起作用。没有autoit怎么办???我想在不加载任何 URL 的情况下执行键盘和鼠标操作,因为我对网站进行了身份验证。

java selenium-webdriver automation selenium-chromedriver
1个回答
0
投票

在 Selenium 中,您通常会等待页面加载,然后再与其交互。但是,如果您需要在页面完全加载之前执行诸如按 ENTER 之类的操作,则可以尝试几种不同的方法。这是结合使用线程和 Selenium 中的 ActionChains 类来实现此目的的一种方法:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import threading
import time

# Function to perform the ENTER key press
def press_enter(driver):
    time.sleep(2)  # Adjust the sleep time as needed for the page to start loading
    actions = ActionChains(driver)
    actions.send_keys(Keys.ENTER)
    actions.perform()

# Set up the driver
driver = webdriver.Chrome()  # Replace with your browser's driver

# Start the thread that will perform the ENTER key press
thread = threading.Thread(target=press_enter, args=(driver,))
thread.start()

# Load the URL
driver.get('http://your-url.com')

# Wait for the thread to finish if necessary
thread.join()

# Continue with your automation tasks

代码的作用如下:

它定义了一个函数 press_enter 等待一小段时间(使用 time.sleep),然后使用 ActionChains 将 ENTER 键按下发送到浏览器。 它设置 WebDriver 并启动一个新线程来运行 press_enter 函数。 它开始使用 driver.get 加载页面。 如果您需要确保在继续之前已按下 ENTER 键,它将等待线程使用 thread.join() 完成。 请注意,通常不建议使用 time.sleep,因为它引入了固定的等待时间。但是,在本例中,它用于确保在页面开始加载之后但完全加载之前按下 ENTER 键。

© www.soinside.com 2019 - 2024. All rights reserved.