'Selecting an element with conditions and multiple attributes using Python's Selenium

I'm having trouble accessing a specific span with selenium. I want to click on a specific search result if the spans texts match a specific string from the website https://www.superherodb.com/battle/create/#add_member

The html code:

<span>
<img src="/pictures2/portraits/10/025/791.jpg" class="avatar avatar-sm" alt="Superman"> Superman
<span class="suffix level-1">Kal-El</span>
<span class="suffix level-2">Prime Earth</span>
</span>

I want to check if the string from the first span = Superman, and second span = Kal-El, and third span= Prime Earth, match the strings on a list.

My code:

driver = webdriver.Chrome('C:\Webdriver\chromedriver.exe', options= options)
driver.get('https://www.superherodb.com/battle/create')
wait = WebDriverWait(driver, 5)

wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="team1"]/div/a'))).click()

Superheroes = ["Superman", "Spiderman"] #check in span
Names = ["Kal-El", "Peter Parker"] #check in span class = "suffix level-1"
Universes = ["Prime Earth", "Prime, Earth"] #check in span class = "suffix level-1"

wait.until(EC.visibility_of_element_located((By.NAME, 'quickselect'))).send_keys(Superheroes[0]) #Search for Superman

search = [my_elem for my_elem in WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH,
 ".//*[@id='quickselect_result']/li/span/[contains(text(), Superheroes[0] )]/.."))) 
 if
my elem in WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH,
 ".//*[@id='quickselect_result']/li/span/span[1][@class='suffix level-1'  and contains(text(), Names[0] )]/.."))) 
 if 
my_elem in WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH,
 ".//*[@id='quickselect_result']/li/span/span[2][@class='suffix level-2'  and contains(text(), Universes [0])]/..")))
 
  ] 

search.click()




My Error:

InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression .//*[@id='quickselect_result']/li/span/[contains(text(), Superheroes[0] )]/.. because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string './/*[@id='quickselect_result']/li/span/[contains(text(), Superheroes[0] )]/..' is not a valid XPath expression.

I want to ultimately turn this into a for loop to check a huge list of Superheroes but I want to select the right one from the list because there are many versions of the same Superhero (i.e. same Superhero, but different Universe).

What am I doing that is wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source