【问题标题】:My WebDriverWait is returning a "dict" instead of the required element我的 WebDriverWait 返回一个“dict”而不是所需的元素
【发布时间】:2021-10-22 02:25:46
【问题描述】:

我想使用 Selenium 和 Gauge 从网页中获取数据。我使用wait_for_element编写了以下代码:

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from step_impl.mixins.exception import MixinException

class MixinSelector(MixinException):

    def __init__(self, driver=None):
        super(MixinSelector, self).__init__(driver)
        self.wait_for_element_time = 60

    def wait_for_elem(self, by, locator_string):
        try:
            element = WebDriverWait(self.driver,self.wait_for_element_time)
                      .until(EC.presence_of_element_located((by, 
                       locator_string)))
            print(element)
            print(type(element))  
            return element
        except TimeoutException:
            self.fail_test('failed')
        except:
            raise

然而,这会产生一个dict 实例,如调试prints 所示:

{'ELEMENT': '0.8884832448581164-1'}
<class 'dict'>

我这样调用函数:

self.wait_for_elem(By.CSS_SELECTOR, '#baseWebLayoutContainerID')

这是一个问题,因为我需要将结果作为可以在其他几个功能中使用的 Web 元素。我怎样才能得到这个结果?

【问题讨论】:

  • 究竟想要取回什么?那有什么不同,为什么这个结果对你不可用? “元素”到底是什么意思?例如,您是否需要某个特定类的实例?
  • 我将您的问题编辑为remove noise 并明确提出问题。请参阅How to Ask 获取更多指导。
  • 一个网络元素,我现在意识到我没有指定它
  • 另请阅读stackoverflow.com/help/minimal-reproducible-example。我们看不到这样的问题,因为在其他可能的问题中,EC 没有在本地定义。
  • 完成。我很抱歉,有点新。将阅读“如何提问”及其文档。

标签: python selenium-webdriver webdriverwait


【解决方案1】:

不要指望从 WebDriverWait 中返回一个 web 元素,而是在 WebDriverWait 之后添加另一行来获取 web 元素,请参见下面的代码

WebDriverWait(driver, 10).until(EC.presence_of_element_located((by, locator_string)))
element = driver.find_element(by, locator_string) 
return element

如下图所示,它对我很有效

【讨论】:

  • 非常感谢艾哈迈德!几个小时前我确实尝试过...同样的结果。该元素仍然是一个字典
  • 很奇怪,我附上一张图片显示它正在工作。
  • 刚看到图片...嗯,你猜问题出在哪里?我使用这一行: element = self.driver.find_element(by, locator_string) 但结果没有改变。会不会是我的司机之类的?
  • 也许吧!我假设您使用的是 chrome,请通过单击右上角的三个点然后帮助然后关于 google chrome 来更新您的 chrome 浏览器,然后它将自动更新到版本 95,重新启动后,转到 chromedriver.storage.googleapis.com/… 并下载最新的驱动程序。然后再试一次,请告诉我你得到了什么
  • 哦...哦,天哪,就是这样。你是我的英雄艾哈迈德!非常感谢你!我花了 10 多个小时试图弄清楚这一点......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 2012-05-02
相关资源
最近更新 更多