为了账号安全,请及时绑定邮箱和手机立即绑定

消息:没有这样的元素:无法找到元素 Selenium Python

消息:没有这样的元素:无法找到元素 Selenium Python

凤凰求蛊 2023-03-08 14:32:36
我试图点击一个按钮,但收到此错误消息:我试图点击的元素确实存在于页面上,但我不确定为什么它说该元素不存在:Message: no such element: Unable to locate element: {"method":"xpath","selector":"//button[@class="vote_button mfp-voteText"]"}下面是我的代码:driver.get('https://trupanion.com/canada/members/contest?pixlee_album_photo_id=427049511')time.sleep(10)try:    vote = driver.find_element_by_xpath('//button[@class="vote_button mfp-voteText"]')    vote.click()except Exception as e:    print(e)下面是 chrome 开发工具中的 XPath,显示它是正确的:
查看完整描述

3 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

所需的元素在 中,<iframe>因此您必须:

driver.get('https://trupanion.com/members/contest?pixlee_album_photo_id=427049511')

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#pixlee_lightbox_iframe")))

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.vote_button.mfp-voteText"))).send_keys("test")

使用XPATH:


driver.get("https://trupanion.com/members/contest?pixlee_album_photo_id=427049511")

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='pixlee_lightbox_iframe']")))

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='vote_button mfp-voteText']"))).click()

注意:您必须添加以下导入:


from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.common.by import By

from selenium.webdriver.support import expected_conditions as EC

浏览器快照:

//img1.sycdn.imooc.com//64082c450001f42f13630766.jpg

查看完整回答
反对 回复 2023-03-08
?
子衿沉夜

TA贡献1828条经验 获得超3个赞

尝试使用css selector而不是XPATH使用函数WebdriverWait()。它将等待 X 秒让元素可点击,并在元素出现后立即点击它。但是,您需要切换到必须通过选择器找到的框架frame。


from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC


self.webdriver.switch_to_frame(self.webdriver.find_element_by_css_selector('frame'))

try:

    WebDriverWait(webdriver,time).until(EC.element_to_be_clickable((By.CSS_SELECTOR,path)))

except Exception as e:

   print(e)


查看完整回答
反对 回复 2023-03-08
?
噜噜哒

TA贡献1784条经验 获得超7个赞

它在<frame>标签内,先切换它:


driver.get('https://trupanion.com/canada/members/contest?pixlee_album_photo_id=427049511')


time.sleep(10)


try:

    #switch it first

    driver.switch_to.frame(driver.find_element_by_id('pixlee_lightbox_iframe'))

    vote = driver.find_element_by_xpath('//button[@class="vote_button mfp-voteText"]')

    vote.click()

except Exception as e:

    print(e)

但是注意time.sleep(..)是个坏主意。


您可以在这里学习硒等待:


selenium-python.readthedocs.io/waits.html


并切换一个框架:


.frame_to_be_available_and_switch_to_it


尽管您的 xpath 可以工作,但 css 选择器看起来更好:


vote = driver.find_element_by_css_selector('button.vote_button.mfp-voteText')


查看完整回答
反对 回复 2023-03-08
  • 3 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信