如何从 Selenium 获取元素的属性
- 2025-01-08 08:50:00
- admin 原创
- 90
问题描述:
我正在 Python 中使用 Selenium。我想获取.val()
某个<select>
元素的并检查它是否符合我的预期。
这是我的代码:
def test_chart_renders_from_url(self):
url = 'http://localhost:8000/analyse/'
self.browser.get(url)
org = driver.find_element_by_id('org')
# Find the value of org?
我该怎么做?Selenium 文档似乎有很多关于选择元素的内容,但没有关于属性的内容。
解决方案 1:
您可能正在寻找。此处也get_attribute()
显示了一个示例
def test_chart_renders_from_url(self):
url = 'http://localhost:8000/analyse/'
self.browser.get(url)
org = driver.find_element_by_id('org')
# Find the value of org?
val = org.get_attribute("attribute name")
解决方案 2:
Python
element.get_attribute("attribute name")
Java
element.getAttribute("attribute name")
红宝石
element.attribute("attribute name")
代码#
element.GetAttribute("attribute name");
解决方案 3:
由于最近开发的Web 应用程序正在使用JavaScript、jQuery、AngularJS、ReactJS等,因此有可能要通过Selenium检索元素的属性,您必须在尝试检索任何属性之前诱导WebDriverWait将WebDriver实例与滞后的Web 客户端(即Web 浏览器)同步。
一些例子:
Python:
要从可见元素(例如
<h1>
标签)检索任何属性,您需要使用expected_conditions作为visibility_of_element_located(locator),如下所示:
attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
要从交互元素(例如
<input>
标签)检索任何属性,您需要使用expected_conditions作为element_to_be_clickable(locator),如下所示:
attribute_value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "org"))).get_attribute("attribute_name")
HTML 属性
下面是 HTML 中经常使用的一些属性的列表
注意:每个 HTML 元素的所有属性的完整列表列在:HTML 属性参考
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD