In the web page, there is many elements like this below and I want to find all of them and click one after one. they have the same name of class but different by ID.
How I can find it and click?
<a class="do do-task btn btn-sm btn-primary btn-block" href="javascript:;" data-task-id="1687466" data-service-type="3" data-do-class="do-task" data-getcomment-href="/tasks/getcomment/" data-check-count="0" data-max-check-count="2" data-money-text="0.08"><font style="vertical-align: inherit;"><font style="vertical-align: inherit;">0.08 </font></font><i class="far fa-ruble-sign"></i></a>
CodePudding user response:
To identify all of the similar elements and create a list you have to induce WebDriverWait for visibility_of_all_elements_located()
and you can use either of the following Locator Strategies:
Using
CSS_SELECTOR
:element_list = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "a.do.do-task.btn.btn-sm.btn-primary.btn-block[data-task-id]")))
Using
XPATH
:element_list = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//a[@class='do do-task btn btn-sm btn-primary btn-block' and @data-task-id]")))
Next, you can access each list item and invoke click()
on each of them one by one.
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
CodePudding user response:
If this css
a.do.do-task.btn.btn-sm.btn-primary.btn-block
represent them, then you can use the below code :
for a in driver.find_elements_by_css_selector("a.do.do-task.btn.btn-sm.btn-primary.btn-block"):
a.click()
You may have to scroll to each element or put some delay before click, this depends on your use case and your automation strategy.