【问题标题】:Selenium Python XPATH Can i print the value of an html tag id attribute to the consoleSelenium Python XPATH我可以将html标签id属性的值打印到控制台吗
【发布时间】: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


【解决方案1】:

或者,您可以将 XPath 更改为如下所示,以返回带有 id 且还包含 button 元素的元素:

//*[starts-with(@id,"operations_add_process_list_task")][.//span//button]

或者,如果 span 是目标为 id 的元素的直接子元素,您可能想要使用 child 轴而不是 //,因为前者会稍微更有效率:

//*[starts-with(@id,"operations_add_process_list_task")][span/button]

【讨论】:

  • 酷,感谢您的帮助
猜你喜欢
  • 2011-09-12
  • 2021-07-16
  • 2016-07-17
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 2015-09-05
  • 1970-01-01
  • 2010-09-30
相关资源
最近更新 更多