【问题标题】:How to wait for the combination of a CSS and an XPath selector in Python WebDriver?如何在 Python WebDriver 中等待 CSS 和 XPath 选择器的组合?
【发布时间】:2019-04-02 23:08:09
【问题描述】:

我希望尽可能让我的选择器保持简单,并且只在绝对必要的情况下使用 XPath。因此,与其等待像 //*[@class='files']/tbody/tr[1]/th[text()='filename'] 这样的 XPath,我更愿意等待简单 CSS 选择器 .files tbody tr:first-child 和简单 XPath th[text()='filename']组合

presence_of_element_located 只需要一个定位器,所以presence_of_element_located((By.CSS_SELECTOR, '.files tbody tr:first-child'), (By.XPATH, 'th[text()='filename']')) 不可用。

我也不能链接这些函数,所以presence_of_element_located((By.CSS_SELECTOR, '.files tbody tr:first-child')).presence_of_element_located((By.XPATH, 'th[text()='filename']')) 不起作用。

【问题讨论】:

    标签: python selenium selenium-webdriver xpath css-selectors


    【解决方案1】:

    您可以创建自定义方法:

    def find_element_by_combo(self, ancestor_locator, descendant_locator, timeout=10, index=0):
        # Getting list of ancestors
        try:
            ancestors =  wait(self, timeout).until(EC.presence_of_all_elements_located(ancestor_locator))
        except:
            return None
        # Getting descendant
        for ancestor in ancestors:
            if ancestor.find_elements(*descendant_locator):
                return ancestor.find_elements(*descendant_locator)[index]
    

    并如下使用它

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait as wait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver import Chrome
    
    Chrome.find_element_by_combo = find_element_by_combo
    
    driver = Chrome()
    driver.get(URL)
    driver.find_element_by_combo(('css', '.files tbody tr:first-child'), ('xpath', './th[text()="filename"]'))
    

    但是恕我直言,在复杂情况下最好只使用 XPath

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-03
      • 2015-01-22
      • 2014-09-01
      • 2014-02-06
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      相关资源
      最近更新 更多