I need to click on several elements from the same table on the same webpage. I was thinking to do so with a for loop but in order to perform that action I first need to create a list of these elements.
//table[@border='1']//a
This is the xpath which selects all the elements from the table, how can I create a list of all these?
解决方案
While @SergiyKonoplyaniy answer was in the right direction, addressing your queries one by one:
How can I create a list of elements with the same xpath : To create a list of elements you need to use find_elements_by_xpath(xpath) which will create a List of elements matching the xpath you have specified.
Example:
my_links = driver.find_elements_by_xpath("//table[@border='1']//a")
Need to click on several elements: As you need to click() on several elements you have to iterate through all the elements you have captured in the List as follows:
for link in my_links:
link.click()
Now the most important aspect is, as per your xpath //table[@border='1']//a each and every element:
Has 3 distinct stages interms of presence, visibility and interactibility (i.e. clickability)
To collect the elements in a List you should always invoke a waiter with expected-conditions as visibility_of_all_elements_located(locator) as follows:
my_list = WebDriverWait(driver, 20).until(expected_conditions.visibility_of_all_elements_located((By.XPATH, "//table[@border='1']//a")))
The pseudo code as a solution for your question will be:
my_links = WebDriverWait(driver, 20).until(expected_conditions.visibility_of_all_elements_located((By.XPATH, "//table[@border='1']//a")))
for link in my_links:
link.click()
For your future reference, if you intend to invoke click() on any particular element always invoke a waiter with expected-conditions as element_to_be_clickable(locator) as follows:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "desired_element_xpath"))).click()