How can I click on random link on a given webpage using selenium API for python. ? I'm using python 2.7. Thanks
-
Why on earth do you need to click a random link? Where's the value in doing that?Arran– Arran2013-06-07 09:09:02 +00:00Commented Jun 7, 2013 at 9:09
-
@Arran it's useful for automatic traffic generation taskrokpoto.com– rokpoto.com2013-06-07 09:34:15 +00:00Commented Jun 7, 2013 at 9:34
-
I need for checking if frame was refreshed.imbr– imbr2020-06-12 16:18:28 +00:00Commented Jun 12, 2020 at 16:18
3 Answers
find_elements_by_tagname() will surely work. There is another option also. You can use find_elements_by_partial_link_text where you can pass empty string.
>>> from selenium import webdriver
>>> from random import randint
>>> driver = webdriver.Firefox()
>>> driver.get('http://www.python.org')
>>> links = driver.find_elements_by_partial_link_text('')
>>> l = links[randint(0, len(links)-1)]
>>> l.click()
2 Comments
l = choice(links) after importing choice from random moduledriver = webdriver.Firefox()
driver.get('https://www.youtube.com/watch?v=hhR3DwzV2eA')
# store the current url in a variable
current_page = driver.current_url
# create an infinite loop
while True:
try:
# find element using css selector
links = driver.find_elements_by_css_selector('.content-link.spf-link.yt-uix-sessionlink.spf-link')
# create a list and chose a random link
l = links[randint(0, len(links) - 1)]
# click link
l.click()
# check link
new_page = driver.current_url
# if link is the same, keep looping
if new_page == current_page:
continue
else:
# break loop if you are in a new url
break
except:
continue
Creating a list work, but if you are having problems like me use this code if you keep getting Timeout Error or your webdriver isn't consistently clicking the link.
As an example I used a YT video. Say you want to click a recommended video on the right side, well, it has a unique css selector for those links.
The reason why you want to make an infinite loop is b/c when when you make a list of elements, for some reason, python doesn't do a good job expressing stored elements. Be sure you have a catch all 'except' b/c you will get Timeout Errors and such and you want to force it to click on the random link.