One more good option is to use ancestor in xpath. I bound the main locator to the table name, it would be more reliable.
Using it you can find other locators and their text. Just put them to the loop with correct paths.
In the child xpath .//td means a direct child of the main locator with element name td.
My solution:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
url = 'https://s5.sir.sportradar.com/sports4africa/en/1/season/80526/headtohead/334075/340986/match/27195664'
driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')
driver.get(url)
driver.implicitly_wait(10)
WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located((By.XPATH, "//strong[text()='Last matches']/ancestor::div[6]//tbody/tr")))
rows= driver.find_elements_by_xpath("//strong[text()='Last matches']/ancestor::div[6]//tbody/tr")
output = []
for res in rows:
score = res.find_element_by_xpath(".//td[5]//div[@class=' no-wrap']").get_attribute("innerText")
output.append(score)
print(output)
Output:
First link:
['0:4', '3:4', '2:2', '0:1', '3:0', '2:2', '0:4', '1:0', '2:1', '1:1', '1:2', '2:4']
Second link:
['2:0', '2:1', '0:2', '0:0', '4:2', '1:0', '3:0', '1:1', '1:0', '2:1', '1:1', '0:8']
Update:
The fastest way to swap scores I could do is with getting two scores separately, placing them in a separate lists and swapping using zip.
The results are two lists of tuples.
first_score = []
second_score = []
for res in rows:
first = res.find_element_by_xpath(".//td[5]//div[@class=' no-wrap']/div[1]").get_attribute("innerText")
first_score.append(first)
second = res.find_element_by_xpath(".//td[5]//div[@class=' no-wrap']/div[3]").get_attribute("innerText")
second_score.append(second)
first_list = list(zip(first_score, second_score))
second_list = list(zip(second_score, first_score))
print(first_list)
print(second_list)
The results are two lists of tuples.
[('0', '4'), ('3', '4'), ('2', '2'), ('0', '1'), ('3', '0'), ('2', '2'), ('0', '4'), ('1', '0'), ('2', '1'), ('1', '1'), ('1', '2'), ('2', '4')]
[('4', '0'), ('4', '3'), ('2', '2'), ('1', '0'), ('0', '3'), ('2', '2'), ('4', '0'), ('0', '1'), ('1', '2'), ('1', '1'), ('2', '1'), ('4', '2')]
There are more effective ways to do it, but I'd suggest to ask a separate question for it.