当前位置: 代码迷 >> python >> Python Selenium无法通过xpath在页面上找到元素
  详细解决方案

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

热度:74   发布时间:2023-06-19 09:18:32.0

我正在使用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)

谢谢你的帮助。

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

disneyid的iframe

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

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

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

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

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

在python中使用XPath您需要提供字符串

driver.find_element_by_xpath 

下面的示例代码

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

请参考以下有关字符串的文档