首页 > 解决方案 > 如何在存在的搜索字段元素中第二次发送_keys

问题描述

该网站是https://www.webstaurantstore.com/25887/commercial-gas-ranges.html?page=1。当我想本地化右上角的搜索字段并在那里发送密钥时,它可以工作。但是当我想在执行一次搜索后执行相同的操作时,它不起作用。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)

标签: pythonseleniumxpathcss-selectorswebdriverwait

解决方案


poll_frequency - 在调用之间休眠并在捕获异常时刷新页面。

 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()

推荐阅读