我安装了Anaconda3,使用Python 3.6。现在安装了Selenium 3.8和webdriver,例如IE浏览器。 Web浏览器启动并显示google页面,但find_element_by_name不起作用。我调查了网页,搜索栏的名称为" q"。你能帮忙吗?
这是我的代码:
from selenium import webdriver
browser = webdriver.Ie()
browser.get('https://google.de')
elem = browser.find_element_by_name('q')
错误代码:
Traceback (most recent call last):
File "Testbot.py", line 4, in <module>
elem = browser.find_element_by_name('q')
File "C:\Users\User\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 440, in find_element_by_name
return self.find_element(by=By.NAME, value=name)
File "C:\Users\User\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 858, in find_element
'value': value})['value']
File "C:\Users\User\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 311, in execute
self.error_handler.check_response(response)
File "C:\Users\User\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 237, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to find element with css selector == [name="q"]
答案 0 :(得分:1)
我在代码块中没有看到任何错误。但是当您使用 anaconda3
时,一个简单的解决方案就是为 WebDriverWait
诱导 Search Box
https://google.de
为clickable
,如下所示:
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
browser = webdriver.Ie()
browser.get('https://google.de')
elem = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.NAME, "q")))
答案 1 :(得分:0)
很可能该元素尚未出现在页面上(它未加载)。尝试添加browser.implicitly_wait(10)以确保在失败之前重试几次,或者您可以添加显式等待元素。你应该看看http://selenium-python.readthedocs.io/waits.html