【问题标题】:Selenium: Can't find element by class name in any waySelenium:无法以任何方式按类名查找元素
【发布时间】:2022-11-05 06:00:37
【问题描述】:

我有这个问题,我无法以任何我能想到的方式通过其类名访问按钮。 这是 HTML:

<button class="expand-button">
 
 <faceplate-number pretty="" number="18591"><!---->18.591</faceplate-number> weitere Kommentare anzeigen
 
 </button>

我尝试使用以下方式访问它:

driver.find_element(By.CLASS_NAME, "expand-button")

但是错误告诉我没有这样的元素。 我还尝试了 X-Path 和 Css-Selector,它们似乎都不起作用。

我会很高兴有任何帮助!
预先致以亲切的问候和感谢
埃里克

【问题讨论】:

  • 如果该元素是使用 javascript 动态创建的,则问题可能是您在浏览器有足够时间创建元素之前过早地查找该元素。
  • 你能分享你所有的 selenium 代码,包括你正在处理的页面的链接吗?您的问题可能由多种原因引起:缺少延迟、iframe、新标签等。我们需要更多详细信息
  • 这很难做到,因为我在 webdriver 中使用了扩展
  • 作为一个非常基本的测试,尝试打印driver.page_source 以直观地确认该元素存在。
  • 另外我刚刚发现的是我试图访问的内容是在 #shadow root (open) 里面

标签: python selenium


【解决方案1】:

可能的问题 1

这可能是因为您在 DOM 中创建元素之前进行了检查。

解决此问题的一种方法是使用如下所示的 waites 选项

driver.implicitly_wait(10)
driver.get("http://somedomain/url_that_delays_loading")
my_dynamic_element = driver.find_element(By.ID, "myDynamicElement")

你可以在这里阅读更多信息:https://www.selenium.dev/documentation/webdriver/waits/#implicit-wait

另一种方法是使用 Fluent Wait 标记 Selenium WebDriver 等待某个条件(Web 元素)变为可见的最长时间。它还定义了 WebDriver 在抛出“ElementNotVisibleException”之前检查条件是否出现的频率。

#Declare and initialise a fluent wait
FluentWait wait = new FluentWait(driver);
#Specify the timout of the wait
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
#Sepcify polling time
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
#Specify what exceptions to ignore
wait.ignoring(NoSuchElementException.class)
#specify the condition to wait on.
wait.until(ExpectedConditions.element_to_be_selected(your_element_here));

您还可以从官方文档中了解更多信息 https://www.selenium.dev/documentation/webdriver/waits/#fluentwait

可能的问题 2

也有可能该元素可能被覆盖它的元素部分或完全阻挡。如果是这种情况,那么您必须先关闭覆盖元素,然后才能对目标执行任何操作

【讨论】:

    猜你喜欢
    • 2020-05-19
    • 2020-03-05
    • 2021-03-05
    • 2023-01-03
    • 1970-01-01
    • 2015-07-12
    • 2015-01-18
    • 1970-01-01
    相关资源
    最近更新 更多