【问题标题】:What is a Selenium locator in Python specifically?Python 中的 Selenium 定位器具体是什么?
【发布时间】:2023-01-19 10:02:15
【问题描述】:

我的问题来自试图理解以下代码(这意味着在继续之前等待特定元素加载到页面上):

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# ... start chromium_driver 

wait_timeout = 10
wait = WebDriverWait(chromium_driver, wait_timeout)

target_id = "CookiePopup"
target_element = wait.until(EC.presence_of_element_located((By.ID, target_id)))

我可以理解定位器在概念上是什么(“a way to identify elements on a page”),但我试图将其结构和规范作为此上下文中的对象(即EC.presence_of_element_located(locator) 的签名)。注意,上面代码中的 (By.ID, target_id) 部分需要括在括号内; IE。,

EC.presence_of_element_located(By.ID, target_id)

原因

TypeError: __init__() takes 2 positional arguments but 3 were given

该文档解释说“[定位器] 是传递给查找元素方法的参数”。

Finding element methods页面显示Python中的find_element()方法有两个参数,这是我觉得有些混乱的部分:

vegetable = driver.find_element(By.CLASS_NAME, "tomatoes")

此外,By.CLASS_NAMEBy.ID等实际上是包含字符串的属性(分别为“类名”和“id”)。

将此与 Java(或任何其他语言)代码进行比较:

WebElement vegetable = driver.findElement(By.className("tomatoes"));

这更有意义:By.className() 是一种方法,它将 (HTML) 类名作为参数并返回一个定位器对象,该对象与具有该类名的元素相匹配。

鉴于以上情况,描述定位器作为一个元组两个海峡,第一个字符串是所用标识符的类型,第二个字符串是该标识符的值?作为后续问题,为什么 Python 在这方面与其他语言不同?

【问题讨论】:

    标签: python selenium expected-condition


    【解决方案1】:

    文档并没有说清楚(无论如何对我来说)为什么你必须传递括号中的参数,但在这里查看该函数的源代码:

    https://www.selenium.dev/selenium/docs/api/py/_modules/selenium/webdriver/support/expected_conditions.html#presence_of_element_located

    您可以看到,在 presence_of_element_located() 的实现中,它将您传递的任何内容作为定位器,并在对 find_element(*locator) 的调用中传递该参数

    请注意,星号 (*) 在 Python 中用于解压缩元组(或任何可迭代对象)的内容。有关这方面的更多信息,请参阅此答案:

    https://stackoverflow.com/a/1993732

    【讨论】:

      猜你喜欢
      • 2018-09-05
      • 2020-02-03
      • 1970-01-01
      • 2020-10-24
      • 2016-08-31
      • 2018-08-20
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多