1

I have the following class:

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)

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?

1 Answer 1

1

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

  • Using variable:

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

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

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

You can implement it like:

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)
Sign up to request clarification or add additional context in comments.

6 Comments

Yes, I am using variable but I get the error message: CHOOSE_SECTION_SEL = (By.XPATH, "//*[@class='select2-result-label' and (text() = '" + state + "')]") NameError: name 'state' is not defined
@bbfl Checkout the answer update and let me know the status.
Thanks, it works but basically it is almost the same as my second example which also works. However is there a another way CHOOSE_SECTION_SEL = (By.XPATH, "//*[@class='select2-result-label' and text()='" + state + "']") not be inside a function?
@bbfl Then the variable state needs to have global scope which you may like to avoid.
thanks a lot. Yes, it worked as you suggested and seems this is the most optimal way to do it!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.