您可以创建自定义方法:
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"]'))