【问题标题】:Python selenium webdriver element not found找不到 Python selenium webdriver 元素
【发布时间】:2021-03-16 03:07:34
【问题描述】:

我正在做一个网络自动化项目,但我卡在一个按钮上 我的 python 程序无法找到该过滤器按钮的元素

那个按钮的html代码是

<a role="button" class="list_filter_toggle icon-filter btn btn-icon" tabindex="0" 
title="" id="task_filter_toggle_image" 
aria-controls="taskfilterdiv" 
aria-expanded="false" data-original-title="Show / hide filter"><span 
class="sr-only">Show / hide filter</span></a>

我的代码是

btn=browser.find_element_by_xpath("//*[contains(text(), 'Show / hide filter'")
btn.click()

错误信息

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an 
element with the xpath expression //*[contains(text(), 'Show / hide filter' because of the following 
error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[contains(text(), 'Show / 
hide filter'' is not a valid XPath expression.
(Session info: chrome=89.0.4389.82)
Stacktrace:
Backtrace:

请帮帮我,我需要点击按钮但找不到按钮元素

【问题讨论】:

  • 如果你使用会发生什么:find_element_by_id("task_filter_toggle_image")
  • 您缺少 (text 的右括号。还有 [contains 的右方括号。
  • 试试find_elements_by_class_name()方法
  • 使用ID查找A标签有什么问题?
  • with find_element_by_id("task_filter_toggle_image") 出现错误 -------------- raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: 消息:没有这样的元素:无法找到元素:{"method":"css selector","selector":"[id="task_filter_toggle_image"]"}(会话信息:chrome=89.0.4389.82)

标签: python selenium


【解决方案1】:
from selenium import webdriver
website = "www.stackoverflow.com"
driver = webdriver.Firefox()
driver.get(website)

e = driver.find_element_by_xpath("//*[text()='Show / hide filter']")

print(e)

【讨论】:

  • selenium.common.exceptions.NoSuchElementException: 消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"//*[text()='显示/隐藏过滤器']"} (Session info: chrome=89.0.4389.82) Stacktrace: ------------ 没有运气仍然报错
  • @DineshSharma 我已经准确地测试了你在 html 中提供的内容,正如你前面提到的,并得到了结果。阅读错误,它说无法找到元素。这不是错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 2016-09-07
  • 2017-10-24
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
相关资源
最近更新 更多