bbfl
bbfl

Reputation: 365

Loop to click on all links with the same CSS_SELECTOR on Python and Selenium

I have the following CSS_SELECTOR which appears between 2 - 20 times on my page and the number changes everyday:

event = driver.find_elements(By.CSS_SELECTOR, ".sport-tennis .event-list .event-column-main")
random = event[randint(0, len(event)-1)]
random.click()

When click on it it takes me to another page which url changes everyday so it is not fixed url. Now as you see I did it by clicking randomly on that css_selector but my question is: is there a way to make a loop which clicks on all of the mentioned above css_selectors without repeating?

EDIT: Tried this but only clicks on the first link with that css_selector and opens the page but then when goes back to the main page doesn't click the second link and just finishes with exit code 0:

events = driver.find_elements(By.CSS_SELECTOR, ".sport-tennis .event-list .event-column-main")

for event in events:
    event.click()
    time.sleep(1)
    driver.find_element(By.CSS_SELECTOR, ".sport-tennis .flex-column .text-truncate").click()
    time.sleep(1)

Upvotes: 0

Views: 161

Answers (2)

Maran Sowthri
Maran Sowthri

Reputation: 878

I doubt that the element state might have changed on the each iteration, so try this,

for i in range(len(events)):
    events = driver.find_elements(By.CSS_SELECTOR, ".sport-tennis .event-list .event-column-main")
    event[i].click()
    time.sleep(1)
    driver.find_element(By.CSS_SELECTOR, ".sport-tennis .flex-column .text-truncate").click()
    time.sleep(1)

Upvotes: 1

Alin Stelian
Alin Stelian

Reputation: 897

Let's call your list events instead of event, event variable will use it later, so your code can be

events = driver.find_elements(By.CSS_SELECTOR, ".sport-tennis .event-list .event-column-main")
for event in events:
    event.click();

Upvotes: 1

Related Questions