Search by xpath and text where text is a string contained within a list



  • 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.

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


  • 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.

    Try:

    "//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()
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2