from selenium import webdriver import time from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome(r"C:\Users\m\Desktop\python\selen\chromedriver.exe") driver.set_page_load_timeout(10) driver.get("https://google.com") driver.find_element_by_name("q").send_keys("Automation") driver.find_element_by_name("btnk").send_keys(Keys.ENTER) time.sleep(4) driver.quit()
我正在尝试用这个简单的代码打开 Google,用上面的代码搜索一些东西。但我收到了这个错误消息:
Traceback (most recent call last): File "C:\Users\m\Desktop\python\selen\auto.py", line 9, in <module> driver.find_element_by_name("btnk").send_keys(Keys.ENTER) File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 496, in find_element_by_name return self.find_element(by=By.NAME, value=name) File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element 'value': value})['value'] File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"name","selector":"btnk"} (Session info: chrome=74.0.3729.131) (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17134 x86_64)
这应该可以解决你的问题:
from selenium import webdriver import time from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome("/usr/bin/chromedriver") driver.set_page_load_timeout(10) driver.get("https://google.com") search = driver.find_element_by_name('q') search.send_keys("google search through python") search.send_keys(Keys.RETURN) time.sleep(4) driver.quit()
我在 Ubuntu + chrome 浏览器上测试过
替换你的代码
driver.find_element_by_name("q").send_keys("Automation") driver.find_element_by_name("btnk").send_keys(Keys.ENTER)
至 =>
search = driver.find_element_by_name('q') search.send_keys("google search through python") search.send_keys(Keys.RETURN)