如何第二次在搜索字段元素中发送_键

2024-04-29 00:21:10 发布

您现在位置:Python中文网/ 问答频道 /正文

该网站是https://www.webstaurantstore.com/25887/commercial-gas-ranges.html?page=1。当我想定位右上角的搜索字段并在那里发送then键时,它就起作用了。但是,当我想在执行一次搜索后执行相同的操作时,它不起作用。selenium可以定位元素,但不能向其发送密钥。为什么会发生这样的事情?我怎样才能避免呢

while True:
    try:
    a = self.webdriver.find_element_by_xpath('/html/body/div[3]/div[1]/div[2]/div[2]/div/div[2]/div/form/div/input')
    except:
        pass
    else:
        a.send_keys(i.text[1:])
        break

错误:

>>>selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=81.0.4044.138)

Tags: https定位divcom网站htmlwwwselenium
3条回答

我认为问题在于您提到的元素已从DOM中删除

这就是为什么会出现异常,元素本身不再存在,即使它显示在UI上。 您可以将try/catch与相同的指令块一起使用

try:
    line1
    line1
    ...

except:
    line1
    line1
    ...

这是一个简单的想法来解决像你这样的问题,但不是最好的解决方案,如果我有更好的答案,我会更新我的答案

要在第一次使用Selenium搜索后第二次将字符序列发送到搜索框,需要为element_to_be_clickable()诱导WebDriverWait,并且可以使用以下任一Locator Strategies

  • CSS_SELECTOR

    driver.get("https://www.webstaurantstore.com/25887/commercial-gas-ranges.html?page=1")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='searchval']"))).send_keys("Oven")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[value='Search']"))).click()
    search = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='searchval']")))
    search.click()
    search.clear()
    search.send_keys("Bowls")
    
  • XPATH

    driver.get("https://www.webstaurantstore.com/25887/commercial-gas-ranges.html?page=1")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='searchval']"))).send_keys("Oven")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@value='Search']"))).click()
    search = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='searchval']")))
    search.click()
    search.clear()
    search.send_keys("Bowls")
    
  • 注意:您必须添加以下导入:

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

轮询_频率-在呼叫之间休眠 如果发现异常,请刷新页面

 try:
        wait = WebDriverWait(driver, 5, poll_frequency=1)
        a = self.webdriver.find_element_by_xpath('/html/body/div[3]/div[1]/div[2]/div[2]/div/div[2]/div/form/div/input')
        element = wait.until(expected_conditions.visibility_of_element_located(a))
    except:
        driver.refresh()

相关问题 更多 >