Python 和 Selenium 脚本和设置焦点不起作用

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

我有一些代码,我打开一个网页,然后尝试将焦点设置在测试框上,以便用户可以开始键入,但是,当页面打开并且光标在正确的文本框上闪烁时,如果用户开始键入URL 栏是输入内容的地方,如何让它显示在文本框中?

    # import the required libraries
import undetected_chromedriver as uc

 
# define Chrome options
options = uc.ChromeOptions()

# set headless to False to run in non-headless mode
options.headless = False

# set up uc.Chrome(use_subprocess=True, options=options)

from arcgis.gis import GIS
from arcgis.geometry import Point, Polyline, Polygon
import datetime
import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager 
import time
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


#driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver = uc.Chrome(use_subprocess=True, options=options)
driver.get("https://library.usask.ca/#gsc.tab=0")



q_field = driver.find_element("id", "primoQueryTemp")
q_field.send_keys("_")
q_field.click()

time.sleep(566)

我尝试过的就在那里 查找元素 发送密钥 甚至 。点击() 但它仍然默认为 URL 框

python selenium-webdriver
1个回答
0
投票

Actions.moveToElement()
从技术上讲,它适用于所有输入字段。

sendKeys("")
可能不适用于所有类型的输入

在某些情况下,即使在测试过程中,使用 JavaScript (

element.focus()
) 和 Selenium 也是关注元素的最可靠方法。

# Import the required libraries
import undetected_chromedriver as uc
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
import time

# Define Chrome options
options = uc.ChromeOptions()

# Set headless to False to run in non-headless mode
options.headless = False

# Chrome driver
driver = uc.Chrome(use_subprocess=True, options=options)

# Go to the desired URL
driver.get("https://library.usask.ca/#gsc.tab=0")

# Wait until the input field is visible
wait = WebDriverWait(driver, 10)
q_field = wait.until(EC.presence_of_element_located((By.ID, "primoQueryTemp")))

# Use JavaScript to focus the element
driver.execute_script("arguments[0].focus();", q_field)

# Initiate typing into the field
q_field.send_keys("_")

# Click the field to trigger any other events
q_field.click()

# Keep the browser open for observation
time.sleep(566)

# Close the driver
driver.quit()
© www.soinside.com 2019 - 2024. All rights reserved.