很难缩小复选框的XPath

2024-05-15 21:05:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在以下网站上练习硒:

你知道吗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\u home\u screen\u组件正常通过,但test\u choose\u 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到我的代码中,最终,我只是从这些东西开始。你知道吗


Tags: instancefromimportselfhomebydefdriver
3条回答

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

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

根据urlhttp://automationpractice.com/index.php?id_category=8&controller=category#/categories-casual_dresses,当您试图调用元素上的click()时,需要使用visibility_of_element_located()方法,而不是visibility_of_element_located()方法,如下所示:

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

只要替换一下

EC.visibility_of_element_located

EC.presence_of_element_located

能够处理所需复选框

相关问题 更多 >