调用类和函数时,Python Selenium中的xpath中的变量 [英] Variable in xpath in Python Selenium when calling Class and Function

查看:71
本文介绍了调用类和函数时,Python Selenium中的xpath中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

class Sections(BasePage):

    CHOOSE_SECTION_SEL = (By.XPATH, "//*[@class='select2-result-label' and (text() = '" + state + "')]")

    def choose_section(self, state):
        self.click_on_element("choose section", self.CHOOSE_SECTION_SEL)

然后我要这样称呼它,以便我可以更改变量'state'到我想要的任何地方,但是它显然不起作用:

Then I want to call it like this so I can change the variable 'state' whatever I want but it is not working obviously:

section = Sections(driver=self.driver)
section.choose_section(state="CALENDAR")

我知道我可以这样做,并且可以正常工作:

I know I can do it like this and it is working:

class Sections:

    def section(self, state):
        driver.find_element_by_xpath("//*[@class='select2-result-label' and (text() = '" + state + "')]").click()

...

choose = Sections()
choose.section(state="CALENDAR")

但是,我必须像第一个示例那样去做.有什么需要改变的想法吗?

However I have to do it like the first example. Any ideas what I have to change?

推荐答案

您可以更改表示为以下两种形式之一:

You can change the xpath notation to either of the following forms:

  • 使用变量:

CHOOSE_SECTION_SEL = (By.XPATH, "//*[@class='select2-result-label' and text()='" + state + "']")

  • 使用%s

    CHOOSE_SECTION_SEL = (By.XPATH, "//*[@class='select2-result-label' and text()='%s']"% str(state))
    

  • 使用 {}

    CHOOSE_SECTION_SEL = (By.XPATH, "//*[@class='select2-result-label' and text()='{}']".format(str(state)))
    

  • 您可以像这样实现它:

    class Sections(BasePage):
    
        def choose_section(self, state):
            self.CHOOSE_SECTION_SEL = (By.XPATH, "//*[@class='select2-result-label' and (text() = '" + state + "')]")
            self.click_on_element("choose section", self.CHOOSE_SECTION_SEL)
    

    这篇关于调用类和函数时,Python Selenium中的xpath中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆