Reputation: 10736
How can I click on random link on a given webpage using selenium API for python. ? I'm using python 2.7. Thanks
Upvotes: 4
Views: 7702
Reputation: 73
driver = 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.
Upvotes: 1
Reputation: 7256
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()
Upvotes: 9
Reputation: 5453
How about generating a list of all available links on the page and then clicking a random element from within that list?
list = driver.find_elements_by_tagname("a")
list[random.Random(0, len(list)].click()
(I hope that's how you use random in python 2.7, I'm a python 3.3 user, sorry)
Upvotes: 0