在尝试在 python 中运行 selenium 命令时,我无法导入 selenium.webdriver.common.by 但是库“selenium”导入得很好。我正在 VS Code 中运行程序
脚本:-
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://**.com")
search_id = "123"
search_elem = driver.find_element(By.ID, search_id)
#search_elem.send_keys("**email.com")
breakpoint()
错误:-
PS C:\Users\Desktop\python selenium> python test.py
DevTools listening on ws://***/devtools/browser/44ebdc50-e0c6-43e6-a329-85c2e96b0892
Traceback (most recent call last):
File "C:\Users\Desktop\python selenium\test.py", line 7, in <module>
search_elem = driver.find_element(By.ID, search_id)
File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 748, in find_element
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 354, in execute
self.error_handler.check_response(response)
File "C:\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="i0116"]"}
(Session info: chrome=128.0.6613.138); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception
您看到的错误与 Selenium 无法在页面上找到该元素有关,而不是具体与导入 By 类有关。以下是排查和解决问题的步骤:
验证按导入 事实上,您的程序到达了搜索元素的位置,这意味着 By 类已成功导入。如果导入出现问题,您会在回溯顶部看到 ImportError。
检查页面上元素的可用性 NoSuchElementException 表明 Selenium 无法在页面上找到该元素。这可能是由于以下几个原因造成的:
页面尚未完全加载:页面加载后该元素可能无法立即可用。在这种情况下,等待元素变得可用会很有帮助。 选择器不正确:确保您要查找的元素的 id 值 (search_id) 正确。 动态内容加载:某些网站使用 JavaScript 动态加载内容,并且该元素可能不存在于初始 HTML 中。 3.引入等待 您可以引入显式或隐式等待,以给予页面加载时间和元素出现时间。
显式等待示例: 蟒蛇
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://**.com")
search_id = "123"
# Wait until the element with the given ID is present (maximum wait time is 10 seconds)
try:
search_elem = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, search_id))
)
# If found, interact with the element
search_elem.send_keys("**email.com")
except Exception as e:
print(f"Error: {e}")
finally:
driver.quit()