如何在Python Selenium中使用xpath或CSS选择器查找元素

时间:2019-08-19 18:45:18

标签: python selenium xpath css-selectors webdriverwait

我需要单击一个下拉菜单按钮。

这是用于切换的下拉按钮。如果单击该按钮,它将下拉并显示一个选项。如果再次单击该按钮,则显示将恢复为原始。

...

<div f-menu-item-submenu="$parent.createMenu" ng-if="!$root.ADMIN_RO &amp;&amp; menu.menuBar" class="ng-scope ng-isolate-scope menu-item menu-item-submenu">
    <button type="button" ng-class="{'selected': selected}" ng-disabled="disabled()" ng-click="onClick($event)">
        <div class="flex-button-content" ng-transclude="">
            <f-icon class="ftnt-add ng-scope"></f-icon><span class="ng-binding ng-scope">
                Create New
            </span><span class="flex-filler"></span><f-icon class="fa-caret-down toggle-indicator">
            </f-icon>
        </div>
    </button>
</div>

首先,我尝试使用xpath查找元素:

elem = driver.find_element_by_xpath("/html/body/section/nav/ul/li[4]/div/ul/li[2]/div/ul/li[1]/a/span")

Python说:

"Unable to locate element".

然后我尝试使用CSS slector查找元素:

elem = driver.find_element_by_css_selector(".left-menu-items > div.ng-scope.ng-isolate-scope.menu-item.menu-item-submenu > button > div > span.ng-binding.ng-scope")

硒仍然说:

"Unable to locate element"

3 个答案:

答案 0 :(得分:1)

似乎您与css_selector距离很近。

所需元素是Angular元素,因此必须在元素上定位click()并为element_to_be_clickable()引入 WebDriverWait ,您可以使用其中一个以下Locator Strategies中的

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.ng-scope.ng-isolate-scope.menu-item.menu-item-submenu > button > div.flex-button-content span.ng-binding.ng-scope"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='ng-scope ng-isolate-scope menu-item menu-item-submenu']/button/div[@class='flex-button-content']//span[@class='ng-binding ng-scope' and contains(., 'Create New')]"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

答案 1 :(得分:0)

您可以使用XPath selector,它会通过normalize-space()函数来依赖于此Create New文本,例如:

//span[normalize-space()='Create New']

演示:

enter image description here

更多信息:XPath Operators & Functions

答案 2 :(得分:0)

正确的XPATH是:

//div[@class='ng-scope ng-isolate-scope menu-item menu-item-submenu']/button

您只需要单击按钮即可。