【问题标题】:Selenium Python find button with <button type="button" class="size-grid-dropdown size-grid-button" data-qa="size-dropdown">AB 12</button>Selenium Python 查找按钮 <button type="button" class="size-grid-dropdown size-grid-button" data-qa="size-dropdown">AB 12</button>
【发布时间】:2020-09-19 17:00:54
【问题描述】:

我正在尝试在 python 中使用 selenium 查找网站中的按钮,并且按钮标识为: AB 12

我正在尝试使用此代码,但都找不到按钮...

driver.find_element_by_xpath("//button[contains(@class, '.size-grid-dropdown .size-grid-button') and contains(.,'AB 12)]")

driver.find_element_by_xpath('//button[span[text()="AB 12"]')

driver.find_element_by_link_text("AB 12")

问题是:我有很多相同类别但 AB 12 / AB 23 / AB 34 不同的按钮...

如何找到精确的按钮?

谢谢!

【问题讨论】:

  • 能否请您发布 DOM 屏幕截图。这样我们也可以尝试检查其他一些属性。
  • find all by class=> 你会得到一个按钮列表 => 循环遍历 => 检查文本是否为 "AB 12" 。根据您提供的 DOM,按钮没有其他唯一标识
  • //button[text()="AB 12"] 有效吗?这是您尝试的第二个的修改版本,没有跨度。

标签: python html selenium class button


【解决方案1】:

假设按钮的id是AB 12,你想要的代码是:

driver.find_element_by_id('AB 12')

您可以看到类似查询的答案:>How to use find_element_by_id() in python 或在此处阅读相同的文档: https://selenium-python.readthedocs.io/api.html#locate-elements-by

事后看来,您想找到一个带有“AB 12”文本的按钮元素 正确的代码是:

driver.find_element_by_xpath('//button[text()="AB 12"]')

您可以查看此类似查询以了解更多变体: How to find button with Selenium by its text inside (Python)?

【讨论】:

  • 嗨,我看到您使用了块引用中的代码,这对您的问题不正确,我将其保留为上下文,请尝试答案末尾的代码,即 driver.find_element_by_xpath(' //button[text()="AB 12"]')
  • 是的,工作...非常感谢,我已经尝试了很长时间...正确答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 2014-12-22
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
相关资源
最近更新 更多