【问题标题】:Python Selenium - 2 buttons with same namePython Selenium - 2个同名按钮
【发布时间】:2020-05-26 15:55:40
【问题描述】:

我正在尝试单击一个按钮,但我无法执行此操作,因为有 2 个具有相似名称类的按钮,我无法单击我想要的按钮。

    Button 1: 
<button class="dropdown-trigger"> 
   <i class="icon2-arrow-down">
      ::before

    Button 2:
<button class="dropdown-trigger is visible-desktop"> 
   <i class="icon2-arrow-down arrow-icon">
      ::before

我只想点击按钮 1,你能帮帮我吗?

【问题讨论】:

  • 你看过locating by XPath吗?
  • 使用基于文本的相关 HTML 更新问题,而不是提供手工制作的 HTML。

标签: python selenium button element


【解决方案1】:

如果你使用的是Chrome浏览器,(我不知道其他浏览器的开发工具,但肯定有类似的东西......)很容易挑选独特的元素。 p>

  1. 按“F12”键打开 Chrome 开发者工具。 (页面可能会刷新。)
  2. 右键单击要聚焦的按钮。
  3. 点击“检查”。
  4. 在浏览器左侧的开发人员工具中,有些地方会发生变化,HTML 源代码中应该有一个灰色框。 (如果您在其上移动鼠标,您检查过的按钮应该会突出显示)
  5. 右键单击灰色线,然后单击“复制 - 复制选择器”。 (根据您的喜好,您可以复制其他特征来查找该元素)
  6. 您现在可以使用复制的选择器(或任何功能)来准确找到您指定的一个元素。

如果您有任何问题,请在本帖留言。谢谢!

【讨论】:

  • 感谢您的回答。但我不明白为什么我需要它。我正在使用 python (selenium),我需要单击一个按钮,我已经尝试过
  • @AndréAlmeida 如果您使用 Chrome 开发人员的工具复制 CSS 选择器,选择器会变得非常具体:只有您右键单击的元素才会被选中。尝试使用driver.find_element_by_css_selector(...)
  • 我收到一条错误消息:selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attach to the page document
  • @AndréAlmeida 那是因为您要选择的元素不在正在运行的 webdriver 浏览器上。尝试将您的网络驱动程序导航到您正在寻找的按钮所在的页面(使用driver.get(...) 函数)。然后尝试按照我发布的方向进行操作!
  • @AndréAlmeida 你一定很辛苦...在执行find_element_by_css_selector 函数时你得到selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page documen 错误吗?好吧,尝试重新加载页面,然后右键单击按钮复制它的css选择器,然后再次执行该功能。发生错误是因为页面或某些 HTML 元素不再有效。
【解决方案2】:

如果你尝试会发生什么

driver.find_element_by_css_selector(".dropdown-trigger.visible-desktop").click()

或者您可以尝试获取显示的两个元素中的元素...

buttons = driver.find_elements_by_class_name('dropdown-trigger')
button = next(filter(lambda x: x.is_displayed() == True, buttons))
button.click()

【讨论】:

  • 在您发送的第一个代码中,我收到此错误:selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector ":".dropdown-trigger.visible-desktop"} 在第二个中它点击了错误的按钮...
猜你喜欢
  • 2016-11-01
  • 2018-03-09
  • 2022-06-30
  • 2021-09-14
  • 2020-09-26
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多