selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:

时间:2019-07-01 10:11:26

标签: python selenium xpath css-selectors webdriverwait

XPath不适用于以下路径代码。

HTML

<span class="voter_details">
 <h4 class="v_msg" id="v_msg" style="font-size: 14px;margin-bottom:25px;">Hi, you are here XXXfor  in a while, kindly enter your name!</h4>
 <input value="" placeholder="Enter your Name" type="text" id="v" name="v" class="form-control name_box" maxlength="20">
 </span>

错误

selenium.common.exceptions.NoSuchElementException: Message: no such element: 
Unable to locate element: {"method":"xpath","selector":"//*[@id='v']"}

代码

driver.find_element(driver.find_element(By.XPATH, "//*[@id='v']")).send_keys('random.choice(list)')

2 个答案:

答案 0 :(得分:1)

使用以下xpath来访问输入元素。

driver.find_element_by_xpath("//input[@placeholder='Enter your Name'][@id='v']").send_keys('Ashwani')

或者您可以使用WebdriverWait等待元素可单击并发送然后输入值。

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//input[@placeholder='Enter your Name'][@id='v']"))).send_keys('Ashwani')

要执行此操作,您需要导入以下内容。

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

答案 1 :(得分:1)

要发送字符序列,您必须诱使 WebDriverWait ,以使元素可点击,并且可以使用以下任一解决方案:

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.form-control.name_box#v[placeholder='Enter your Name']"))).send_keys(random.choice(list))
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='form-control name_box' and @id='v'][@placeholder='Enter your Name']"))).send_keys(random.choice(list))
    
  • 注意:您必须添加以下导入:

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