难以缩小复选框的XPath

时间:2018-06-01 04:28:51

标签: python selenium xpath

我正在以下网站上练习一些Selenium:

www.automationpractice.com

我在下面开始了几项基本测试:

import unittest
from webdriver import Driver
from values import strings
from pageobjects.homescreen import Homescreen


class TestHomeScreen(unittest.TestCase):
    @classmethod
    def setUp(self):
        self.driver = Driver()
        self.driver.navigate(strings.base_url)

    def test_home_screen_components(self):
        home_screen = Homescreen(self.driver)
        home_screen.logo_present()

    def test_choose_dress(self):
        home_screen = Homescreen(self.driver)
        home_screen.choose_dress()

    @classmethod
    def tearDown(self):
        self.driver.instance.quit()

正在阅读以下测试:

from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from values import strings


class Homescreen:

    def __init__(self, driver):
        self.driver = driver

    def logo_present(self):
        self.logo = WebDriverWait(self.driver.instance, 10).until(
            EC.visibility_of_element_located((
                By.ID, "header_logo")))
        assert self.logo.is_displayed()

    def choose_dress(self):
        self.dresses = WebDriverWait(self.driver.instance, 5).until(
            EC.visibility_of_element_located((
                By.XPATH, '//*[@id="block_top_menu"]/ul/li[2]/a')))
        self.dresses.click()
        self.casual_dresses = WebDriverWait(self.driver.instance, 10).until(
            EC.visibility_of_element_located((
                By.XPATH,'//input[@type="checkbox" and @id="layered_category_9"]')))

test_home_screen_components传递正常,但test_choose_dress失败。我已经缩小了它的最终XPATH失败,这是一个复选框,用于"休闲连衣裙"。它无法找到。我已在Chrome中确认此XPATH有效:

self.casual_dresses = WebDriverWait(self.driver.instance, 10).until(
     EC.visibility_of_element_located((
         By.XPATH,'//input[@type="checkbox" and @id="layered_category_9"]')))

在下一页: http://automationpractice.com/index.php?id_category=8&controller=category#/categories-casual_dresses

所以我不确定问题是什么。也许我错过了一些东西,因为它是嵌入式的?

另外我知道我最终还需要为我的代码添加一些Try / Except,我刚刚开始使用这些东西。

3 个答案:

答案 0 :(得分:1)

只需替换

EC.visibility_of_element_located

EC.presence_of_element_located

能够处理所需的复选框

答案 1 :(得分:1)

请将元素休闲装滚动到视图中,然后检查元素是否存在

driver.execute_script("arguments[0].scrollIntoView();", self.casual_dresses)

答案 2 :(得分:1)

根据 url http://automationpractice.com/index.php?id_category=8&controller=category#/categories-casual_dresses向前移动,因为您尝试在元素上调用click()而不是visibility_of_element_located()方法,而是需要使用{{ 3}}方法如下:

self.casual_dresses = WebDriverWait(self.driver.instance, 10).until(EC.element_to_be_clickable((By.XPATH,"//span[@class='checked']/input[@class='checkbox' and @id='layered_category_9']")))