[英]How to get attribute of element from Selenium?
我正在Python中使用Selenium。 我想获取<select>
元素的.val()
并检查它是否是我所期望的。
这是我的代码:
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文档似乎有很多关于选择元素的内容,但是与属性无关。
您可能正在寻找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")
蟒蛇
element.get_attribute("attribute name")
爪哇
element.getAttribute("attribute name")
红宝石
element.attribute("attribute name")
C#
element.GetAttribute("attribute name");
由于最近开发的Web应用程序正在使用JavaScript , jQuery , AngularJS , ReactJS等,因此有可能通过Selenium检索元素的属性,您必须诱使WebDriverWait将WebDriver实例与落后的Web客户端(即之前的Web浏览器)同步尝试检索任何属性。
一些例子:
蟒蛇:
要从可见元素(例如<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>
标记)中检索任何属性,您需要按如下所示将期望条件用作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元素的所有属性的完整列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.