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?

bbfl
  • 277
  • 1
  • 2
  • 16

1 Answers1

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)
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 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 Sep 18 '20 at 09:10
  • @bbfl Checkout the answer update and let me know the status. – undetected Selenium Sep 18 '20 at 09:21
  • 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 Sep 18 '20 at 10:07
  • 1
    @bbfl Then the variable `state` needs to have global scope which you may like to avoid. – undetected Selenium Sep 18 '20 at 10:12
  • 1
    thanks a lot. Yes, it worked as you suggested and seems this is the most optimal way to do it! – bbfl Sep 18 '20 at 11:23
  • @bbfl Feel free to visit [Selenium Chat Room](https://chat.stackoverflow.com/rooms/223360/selenium) and help other users. – undetected Selenium Oct 20 '20 at 18:27