I'm struggling to find a way to search a page by xpath that contains text that I've defined within a list using selenium. If I replace Role_List[y] by "WK" etc., it works fine and I can repeat it 4 times but there's a lot of code after that I wouldn't want to repeat but just gives an error when I try to use Role_List[y] but can't figure out what the problem might be.


for y in range(4):
    z= browser.find_element_by_xpath("//div[contains(@class,'createTeamTabTitle_')and text() = Role_List[y]]")

2 Answers 2


The following code is a raw string:

"//div[contains(@class,'createTeamTabTitle_') and text() = Role_List[y]]"

y is interpreted as a char, not as the loop variable.


"//div[contains(@class,'createTeamTabTitle_') and text() = '%s']" % (Role_List[y])

Or even better, just loop through the list:

for role in Role_List
    browser.find_element_by_xpath("//div[contains(@class,'createTeamTabTitle_') and text() = '%s']" % (role)).click()
  • 2
    Hi your code will search for Role_List["mk"] and not mk
    – PDHide
    Feb 18, 2020 at 13:52

The array is not passed as an array but a string:

enter image description here

so the code is actually checking for an element that contains the text "Role_List[y]

so use below code:

z= browser.find_element_by_xpath("//div[contains(@class,'createTeamTabTitle_')and text() =\""+Role_List[y]+"\"]")
  • Please comment your thoughts when down voting
    – PDHide
    Feb 18, 2020 at 13:51

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.