Python Selenium无法通过xpath在页面上找到元素

时间:2018-09-16 17:17:20

标签: python selenium

我正在使用python和selenium来测试梦幻足球的某些功能。到目前为止,这是我的代码(我刚刚开始)。

import time
from selenium import webdriver

driver = webdriver.Chrome('C:\\Users\\202300Fontenot\\Desktop\\3\\chromedriver.exe')
driver.get('http://games.espn.com/ffl/signin?redir=http%3A%2F%2Fgames.espn.com%2Fffl%2Fclubhouse%3FseasonId%3D2018%26leagueId%3D49607%26teamId%3D4');
driver.implicitly_wait(10)
time.sleep(10)
search_box = driver.find_element_by_xpath('//*[@id="did-ui-view"]/div/section/section/form/section/div[1]/div/label/span[2]/input')
search_box.send_keys('email@icloud.com')
search_box.submit()
time.sleep(5)
driver.quit()

这只是尝试在框中输入电子邮件地址。我每次都会收到此错误:

Traceback (most recent call last):
  File "C:\Users\202300Fontenot\Desktop\3\ESPN.py", line 8, in <module>
    search_box = driver.find_element_by_xpath('//*[@id="did-ui-view"]/div/section/section/form/section/div[1]/div/label/span[2]/input')
  File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 393, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 966, in find_element
    'value': value})['value']
  File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute
    self.error_handler.check_response(response)
  File "C:\Users\202300Fontenot\AppData\Local\Programs\Python\Python36\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":"xpath","selector":"//*[@id="did-ui-view"]/div/section/section/form/section/div[1]/div/label/span[2]/input"}
  (Session info: chrome=69.0.3497.92)
  (Driver info: chromedriver=2.42.591088 (7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT 10.0.16299 x86_64)

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

首先,您需要使用其名称切换到iframe:

  

disneyid-iframe

如果不是唯一选择XPATH,则可以使用CSS选择器:

  

div.field-username-email输入[type ='email']

这将使驱动程序查找并填写您的字段。

答案 1 :(得分:0)

您的问题是,您要选择的输入位于iframe内部。您必须首先告诉驱动程序切换到iframe,然后执行xpath选择。

driver.switch_to.frame("disneyid-iframe")
driver.find_element_by_xpath("//input[@type='email']").send_keys('email@icloud.com')

答案 2 :(得分:0)

在python中使用XPath您需要提供

的字符串
driver.find_element_by_xpath 

下面的示例代码

("//*[@id=\"did-ui-view\"]/div/section/section/form/section/div[1]/div/label/span[2]/input")

请参阅以下有关String的文档

String Gude first Para