首页 > 解决方案 > 无法使用 selenium 和 python 找到引用的 ID

问题描述

我正在尝试从网站中查找 ID 为 (search2) 的搜索框。我已经能够使用以下代码成功登录该网站。

import requests
from tqdm import tqdm
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path=r'C:\chromedriver_win32\chromedriver.exe', chrome_options=options)
driver.implicitly_wait(30)
tgt = "C:\\mypath"
profile = {"plugins.plugins_list": [{"enabled":False, "name":"Chrome PDF Viewer"}],
    "download.default_directory" : tgt}
options.add_experimental_option("prefs",profile)
print(options)
driver.get("http://mylink.com/")
user=driver.find_element_by_id("username")
passw=driver.find_element_by_id("password")
user.send_keys("abc@xyz.com")
passw.send_keys("Pwd")
driver.find_element_by_xpath('/html/body/div[2]/div/div/div[2]/form/div[3]/button').click()
page=driver.find_element_by_id("search2")
print(page)

代码在这里完美运行但是当我添加下面的那一刻我得到一个错误

page.send_keys("abc")

我得到的错误如下。

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

我在这里要做的是登录网站并搜索一些项目并下载结果。我已经尝试过使用代码中提到的隐式等待选项。任何帮助将不胜感激。

标签: python-3.xseleniumselenium-webdriverselenium-chromedriver

解决方案


添加下面的代码就可以了。在程序继续运行后续步骤时,必须使当前线程休眠。

time.sleep(5)

感谢大家。


推荐阅读