gpt4 book ai didi

python - 如何在 Python WebDriver 中等待 CSS 和 XPath 选择器的组合?

转载 作者:行者123 更新时间:2023-11-28 18:06:48 25 4
gpt4 key购买 nike

我希望尽可能保持我的选择器简单,并且只在绝对必要时才使用 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']'))行不通。

最佳答案

您可以创建自定义方法:

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

关于python - 如何在 Python WebDriver 中等待 CSS 和 XPath 选择器的组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53055310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com