【发布时间】:2016-03-11 19:41:51
【问题描述】:
我有一个带有 div 标签的 HTML,它有一个 ID 属性。 ID 值是动态的。 我已经设法构建了一个 XPATH 来定位 ID 属性并将其值放入变量中。 我可以将值打印到控制台吗?我想知道变量有什么值。
我尝试打印以下值,但出现错误: 我试过了:
print id.text
print id.get_attribute("id")
错误是:
AttributeError: 'unicode' object has no attribute 'get_attribute'
AttributeError: 'unicode' object has no attribute 'text'
Selenium Python 代码是:
element = self.driver.find_element(By.XPATH, '//*[starts-with(@id,"operations_add_process_list_task")]//span//button')
id = element.get_attribute("id")
print id.text
XPATH 是:
(By.XPATH, '//*[starts-with(@id,"operations_add_process_list_task")]//span//button')
HTML 是:
<div id="operations_add_process_list_task_2">
<span/>
<span>
<span class="myinlineblock" title="Clean"
style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;empty-cells:show;">
<select tabindex="-1">
</span>
</span>
<span>
<span class="" title="Turn group off or on." style="">
<input type="checkbox" checked="" tabindex="-1"/>
</span>
</span>
<span>
<button class="gwt-Button" title="Add the tasks to the selected group." style="display:block;" type="button">Add tasks
</button>
</span>
</div>
一旦我知道值是什么,我就可以将 ID 用于下一个定位器,例如
select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//div[@id="%s"]/span[2]//select' % id))))
谢谢, 里亚兹
【问题讨论】:
-
print id怎么样? -
你指向的
button对象没有Id属性...你想得到div元素"operations_add_process_list_task_2"的Id吗? -
是的,正如 har07 所指定的,
get_attribute()方法返回一个str,所以在id.text中不需要 -
是的,我想找到包含 operations_add_process_list_task_2 的元素。但是上面还有另一个元素 operations_add_process_list_task_1 这就是为什么我去按钮以便我可以得到正确的元素。如果我使用 operations_add_process_list_task 它会突出显示 2 个元素。如果我添加按钮,它会突出显示我想要的第二个元素。
-
我想获取有按钮的元素的ID值
标签: python-2.7 selenium xpath selenium-webdriver