[Python] Storing a locator in a variable

Discussão em 'Python' iniciado por Stack, Agosto 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm new to Python and I'm using a current Java Selenium project as sort of a learning experience converting it to Python.

    In Java, I could do By buttonSaveLoc = By.id("save-button"); Then, it's easy to use this locator since you don't need to remember the locator data, nor the strategy. Is there an equivalent in Python?

    EDIT:

    I'm looking for the locator and not a web element so it can be used for multiple purposes, eg find_element(LOCATOR) or expected_conditions.some_condition(LOCATOR).

    EXAMPLE:

    // SomePageComponent.java
    public class SomePageComponent extends Page {
    private static final By buttonSaveLoc = By.cssSelector("button[title='Save']");

    public void clickSaveButton() {
    clickElement(buttonSaveLoc);
    }
    }

    // Page.java
    public class Page {
    public void clickElement(@NotNull By locator) {
    goWait().until(ExpectedConditions.elementToBeClickable(locator)).click();
    }
    }


    # somepagecomponent.py
    class SomePageComponent(Page):
    def __init__(self, ctx):
    super().__init__(ctx)
    self.button_save_loc = (By.CSS_SELECTOR, 'button[title="Save"]')

    def save(self):
    self.click_element(*self.button_save_loc)

    # page.py
    class Page:
    def __init__(self, ctx):
    self.browser = ctx.browser
    self.timeout = ctx.browser_timeout

    def click_element(self, locator):
    wait = WebDriverWait(self.browser, self.timeout)
    wait.until(expected_conditions.element_to_be_clickable(locator)).click()

    # scenario_steps.py
    @when('the user saves something')
    def step_impl(ctx):
    something = SomePageComponent(ctx)
    something.save()


    The Python script fails ...

    Note that in the Java example which works, wherever the locator is used, I don't need to remember the strategy to find it (by id, classname, whatever) and I don't need to remember the data (some id or css script).

    Again, the reason I want the locator is for the expected condition element_to_be_clickable() which takes a locator, and not a web element. You can see its use in the snippet I posted.

    Since this seemed hard to pick up on, I'm assuming I'm using this in Python entirely wrong, and there's another way in Python to do the same thing.

    Continue reading...

Compartilhe esta Página