Elsa Li
Elsa Li

Reputation: 775

python selenium click on multiple survey buttons error

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

browser = webdriver.Chrome()
browser.get('https://wj.qq.com/s/2214142/51db') # survey link

# First page - click "Next" button, it works
button = browser.find_element_by_class_name('survey_nextpage') # it works
button.click()


# Second page - click one of the scale button between 1-5 
# it always clicks the first button found. how to set to randomly 
# choose from one of the five buttons?

answer = browser.find_element_by_class_name('star_item') 
answer.click() 

I am new to selenium and testing my code on a survey website link.

The first page - It successfully clicks the "Next" button .

The second page - It contains first button which indicates a 1-5 scale. My code always clicks the first button it found. My goal is to randomly pick a button between 1-5 scale and click it. I tried to write a loop but it does not work.

Any suggestions will be greatly appreciated. Thanks.

Upvotes: 1

Views: 423

Answers (3)

Andrei
Andrei

Reputation: 5637

Lets say you have 5 buttons with tag <button>. Then you can locate this buttons like this:

answers = browser.find_elements_by_xpath('xpath') # gives a list with 5 elements (buttons)

PS if you provide HTML block with all 5 buttons I can find a xPath to them. Then you want to peak randomly one of this buttons. You can do like this:

import random

list = [20, 16, 10, 5];
random.shuffle(list)
print ("Reshuffled list : ",  list)

random.shuffle(list)
print ("Reshuffled list : ",  list)

Output:

Reshuffled list :  [16, 5, 10, 20]
reshuffled list :  [20, 5, 10, 16] 

In your case it would be like this:

import random

answers = browser.find_elements_by_xpath('xpath')
random_list = list(range(len(answers))) # creates a list with ascending numbers 0 ... len(answers)
random.shuffle(random_list)
answers[random_list[0]].click() # click randomly on one of the buttons

Upvotes: 1

Swaroop Humane
Swaroop Humane

Reputation: 1836

import random

options = browser.find_elements_by_xpath("//*[starts-with(@class, 'star_item')]") 

option = random.choice(options)
option.click()

Upvotes: 2

nosklo
nosklo

Reputation: 222852

If all elements have the same class name, you can use the plural elements to use the function that returns a list of the elements instead of just the first one:

answers = browser.find_elements_by_class_name('star_item') 
answers[2].click() 

Upvotes: 2

Related Questions