该网站是 https:/www.webstaurantstore.com25887commercial-gas-ranges.html?page=1 . 当我想把搜索字段定位在右上角并把键发送到那里时,它可以工作。但是当我在执行一次搜索后想进行同样的操作时,却无法正常工作。硒可以定位元素,但无法发送键。为什么会发生这样的情况,如何避免?
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)
我相信问题是你所引用的元素被从DOM中删除了。
这就是为什么你会出现异常,元素本身已经不存在了,即使它显示在用户界面上。
try:
line1
line1
...
except:
line1
line1
...
这是个解决你这种问题的简单想法,但不是最好的解决方案,如果我有更好的解决方案,我会更新我的答案。
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()
要发送一个 字序 至 检索 第一次搜索后第二次使用 硒 你需要诱导 WebDriverWait 对于 element_to_be_clickable()
您可以使用以下任何一种方式 定位策略:
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