无法用硒定位元素

时间:2017-05-21 12:04:55

标签: python selenium

我试图在此网站上找到用户名输入面板:http://mail.qq.com 这是我使用的代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
browser.get("http://mail.qq.com")
delay = 3 
try:
    WebDriverWait(browser, delay).until(EC.presence_of_element_located(browser.find_element_by_id('u')))
    print "Page is ready!"
except TimeoutException:
    print "Loading took too much time!"

以下是我收到的错误消息:

Traceback (most recent call last):
  File "D:/Python27/3.py", line 10, in <module>
    WebDriverWait(browser, delay).until(EC.presence_of_element_located(browser.find_element_by_id('u')))
  File "D:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 285, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "D:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 787, in find_element
    'value': value})['value']
  File "D:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in execute
    self.error_handler.check_response(response)
  File "D:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: Unable to locate element: [id="u"]

有谁知道有什么问题?

2 个答案:

答案 0 :(得分:0)

browser.find_element_by_id('u')抛出异常,驱动程序在输入预期条件之前尝试找到该元素。由于它还不存在,因此NoSuchElementException

此外,presence_of_element_located应该将locator作为参数,而不是WebElement

 WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'u')))

答案 1 :(得分:0)

位于iframe内的身份验证表单。为了能够处理input字段,您应首先切换到iframe

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
browser.get("http://mail.qq.com")
delay = 3 

browser.switch_to.frame("login_frame")

try:
    WebDriverWait(browser, delay).until(EC.presence_of_element_located(('id', 'u')))
    print "Page is ready!"
except TimeoutException:
    print "Loading took too much time!"