简体   繁体   中英

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)

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)

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM