Search code examples
seleniumvariablestextelementcontains

cant find an element with selenium by a specific text the element contains, when i want to search for it by the specific text + a variable


I wanted to find an element by a specific text it contains. That worked well, but here is the problem. There are multiple elements, all with a specific text that Contains "EU" and a Number...

For example: "EU 40" or "EU 30". Now I want to replace the Number by an variable, so that I can decide what number the specific text should contain. Just let me show you my code:

real_size_btn = browser.find_element_by_xpath("//button[text()='EU 40']")
real_size_btn.click()

This code is working, but what does not work is this code:

size = input("size:")
real_size_btn = browser.find_element_by_xpath("//button[text()='EU "+size+"']")
real_size_btn.click()

Every time I run the second code it says: "no such element: Unable to locate element: {"method":"xpath","selector":"//button[text()='EU 41']"}"

Hopefully somebody can solve this Problem, I would appreciate it a lot.

A little edit: This is the main element: EU 40

Above the main element is this element:

<input aria-describedby="pdp-buytools-low-inventory-messaging" id="skuAndSize__26126342" name="skuAndSize" type="radio" class="visually-hidden" value="26126342:7">

And under the main element are pretty much the same elements, but a little bit different because the other elements are other shoe sizes. For example this is an element of an other shoe size:

<label for="skuAndSize__26126330" tabindex="-1" class="css-xf3ahq">EU 39</label>

above this element is this:

<input aria-describedby="pdp-buytools-low-inventory-messaging" id="skuAndSize__26126330" name="skuAndSize" type="radio" class="visually-hidden" value="26126330:6.5">

Hope that helps.


Solution

  • Why don't you use f-strings?

    some_number = "your number"
    real_size_btn = browser.find_element_by_xpath(f"//button[text()='EU {some_number}']")
    

    Furhermore, You can put your numbers to a list like this:

    your_list = [10, 20, 30, 40, 50]
    

    and access them as your_list[0], your_list[1] and so on.