使用xpath单击按钮

2024-04-25 05:39:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试单击此按钮:

        <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
            <div class="ui-dialog-buttonset">
                <button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="button" role="button" aria-disabled="false">
                    <span class="ui-button-text">Create</span>
                </button>
               <button aria-disabled="false" role="button" class="ui-button ui-widget    ui-state-default ui-corner-all ui-button-text-only" type="button">

               <span class="ui-button-text">Close</span>
               </button>
               </div>

我想用xpath来实现。这是我的代码:

^{pr2}$

我也尝试过:

driver.find_element_by_xpath(".//div[22]/div[3]/div/button[1]")

我一直收到错误消息无法定位元素。我要换个定位器吗


Tags: textdivdefaultuionlytypebuttonall
3条回答

有多个问题可能导致这个问题。如果没有该页面的完整来源,就不可能分辨出是谁造成的。几个例子:

  • 按钮是动态加载的吗?如果是这样的话,也许Selenium试图在它真正出现在页面上之前访问它。您可能需要等到元素被加载。

  • 按钮是否在iframe中?在这种情况下,您需要使用driver.switch_到\u帧(). 有关如何切换帧的详细信息,请参见this page

  • 您是否在动态加载其他元素?由于按钮出现在div 22中,这似乎是可能的。这可能会在加载这些元素时更改按钮的XPath。

最后,如果XPath是正确的,那么元素就被加载了,并且您看到的是正确的框架,那么它应该能够找到元素。一种解决方案是,如果您正在编辑页面源代码,则将id属性添加到您尝试单击的按钮上。然后,通过元素的ID来定位元素就很简单了,您可以找到here的文档。请注意,ID必须是唯一的,以确保找到正确的按钮。这也将解决动态加载其他元素的问题。在

试试看

要单击Close按钮-

driver.find_element_by_xpath("//button[@class='ui-button ui-widget    ui-state-default ui-corner-all ui-button-text-only']/following-sibling::span[@class='ui-button-text' and contains(text(),'Close')]").click()

因为CSS是相同的,你可以得到所有的按钮,得到文本,看看它是否是你想要的,然后点击它。我不知道python所以请原谅我的语法错误。在

buttons = driver.find_elements_by_css_selector("button")

for button in buttons:
  if button.text.strip() == "Create":
    button.click()

相关问题 更多 >