代码之家  ›  专栏  ›  技术社区  ›  l0b0

如何在pythonwebdriver中等待CSS和XPath选择器的组合?

  •  3
  • l0b0  · 技术社区  · 6 年前

    我希望尽可能地简化选择器,并且只在绝对必要的地方使用XPath。因此,与其等待类似XPath的 //*[@class='files']/tbody/tr[1]/th[text()='filename'] 我宁愿等着 简单CSS选择器的 .files tbody tr:first-child 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']')) 不起作用。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Andersson    6 年前

    您可以创建自定义方法:

    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"]'))