0

Noob question (1 month of coding):

I wanted to limit the number of videos clicked to only the first 3 (arbitrary number) videos.

I am able to run the code successfully but it will click on all videos. I'm ok with all the videos being opened in new tabs but I was just wondering if there was a way to limit the number of videos being opened.

I tried using loops but was unsuccessful.

Thanks in advance.

'''

from selenium import webdriver
from selenium.webdriver.common.keys import Keys


# open URL
url = 'https://www.youtube.com/user/MegatoadStonie/videos'
driver = webdriver.Chrome()
driver.get(url)


# click on videos
links = driver.find_elements_by_xpath("//a[@id='video-title']")
for x in links:
    x.send_keys(Keys.CONTROL,Keys.ENTER)

'''

David
  • 1

1 Answers1

0

Instead of writing

for x in links:
    x.send_keys(Keys.CONTROL,Keys.ENTER)

you can write

for x in links[:3]:
    x.send_keys(Keys.CONTROL,Keys.ENTER)

This way instead of opening all the links, we open the first three links.

links[:3] is a sublist of links with the 0th through 2nd element of the links array. You can learn more about Python array slicing here: https://stackoverflow.com/a/509295/5139284

mic
  • 1,190
  • 1
  • 17
  • 29
  • Thanks for the reference link. There's a lot of helpful information there. – David May 05 '20 at 00:00
  • @David If this resolved your problem, please upvote it and mark it as an accepted answer by clicking the check mark – mic May 05 '20 at 04:34