首页 > 解决方案 > Python +Selenium 找不到要发送密钥的元素

问题描述

我已经处理了很多天了,不知道如何解决它......

那是我想通过硒得到的元素 在此处输入图像描述

<input name="QUICKSEARCH_STRING" id="QUICKSEARCH_STRING" onfocus="setTimeout('focusSearchElem()', 100);" type="text" value="">


他们都弹出这样的警告

===> 消息:没有这样的元素:无法找到元素:{“method”:“css selector”,“selector”:“[name =”QUICKSEARCH_STRING“]”}(会话信息:铬=79.0.3945.88)

这是我的代码:

import selenium.webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains

my_driver = selenium.webdriver.Chrome()
account_box=my_driver.find_element_by_id('j_username')
account_box.send_keys('my_user_name')

#### I tried many ways to get the element####  

#way 1(get the elemnt by full xpath):
my_driver.implicitly_wait(10)
PlmSearchBox=my_driver.find_element_by_xpath("/html/body/div[5]/div[3]/form/div/div[3]/input") #doesn't work
#

#way 2(get the element by name):
my_driver.implicitly_wait(10)
PlmSearchBox=my_driver.find_element_by_name('QUICKSEARCH_STRING') #doesn't work
#

#way 3(get the element by xpath):
my_driver.implicitly_wait(10)
PlmSearchBox=my_driver.find_element_by_xpath('//*[@id="QUICKSEARCH_STRING"]') #doesn't work
#

#way 4(get the element by id):
my_driver.implicitly_wait(10)
PlmSearchBox=my_driver.find_element_by_id('QUICKSEARCH_STRING') #doesn't work
#

#way 5(get the element by using explicit wait):
PlmSearchBox=wait.until(selenium.webdriver.support.expected_conditions.presence_of_element_located((By.ID, "QUICKSEARCH_STRING")))  #doesn't work
#

PlmSearchBox.send_keys('93-55520-300E')
#############################################


在尝试了这些方法并失败后,我注意到光标在我想要发送密钥的输入框中闪烁。

所以我用

动作链

PlmSearchBox = ActionChains(my_driver)
PlmSearchBox.send_keys('93-55520-300E')
PlmSearchBox.perform()

没有弹出任何错误信息,但输入框仍然是空白。

switch_to.active_element

PlmSearchBox=my_driver.switch_to.active_element
PlmSearchBox.clear
PlmSearchBox.send_keys('93-55520-300E')

结果与 ActionChains 相同。

我真的很感激有人告诉我我的代码有什么问题。

标签: python-3.xseleniumxpathcss-selectorswebdriverwait

解决方案


由于您的用例是发送一个字符序列,因此presence_of_element_located()您必须为element_to_be_clickable()and 诱导 WebDriverWait 而不是使用,您可以使用以下任一 定位器策略

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#QUICKSEARCH_STRING[name='QUICKSEARCH_STRING'][onfocus*='focusSearchElem']"))).send_keys("93-55520-300E")
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='QUICKSEARCH_STRING' and @name='QUICKSEARCH_STRING'][contains(@onfocus, 'focusSearchElem']"))).send_keys("93-55520-300E")
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

推荐阅读