Reputation: 391
I am using Selenium to test a site, the idea is to get all rows
from a table
, select the visible buttons
then click
them. Once clicked an event is triggered and with AJAX data is loaded right under the rows
.
The following code works perfectly inside the Firefox console. Actually clicks so fast that items are all loaded at once (there are max 10 rows so I would not bother to add a wait event).
function button_visible(row) {
var opacity = row.style.opacity;
if (opacity == "" || opacity == 1) {
return true;
} else {
return false;
}
}
var table = document.querySelectorAll('div>.table');
for (x = 1; x < table.length; x++) {
row = table.item(x);
var row_buttons = row.querySelectorAll('icon-button');
for (var i = 0; i < row_buttons.length; i++) {
if (button_visible(row_buttons.item(i))) {
row_buttons.item(i).click();
}
}
}
Running this JavaScript from Selenium doesn't not work:
js='function button_visible(row) {var opacity = row.style.opacity; if (opacity === "" || opacity == 1) {return true;} else {return false;}} var table = document.querySelectorAll('div>.table'); for (x = 1; x < table.length; x++) {var row = table.item(x); var row_buttons = row.querySelectorAll('icon-button'); for (var i = 0; i < row_buttons.length; i++) {if(button_visible(row_buttons.item(i))){ row_buttons.item(i).click();}}}'
driver.execute_script(js)
Added come console.log
's, they show up in the console but the click event is not triggered at all. Funny enough, after trying to run the code with Selenium, running the JavaScript from console does not work as well.
I also tried to return these rows
as an array
and click with Selenium but this just makes things complicated as I get stale element exception. To make sure it works I need to re-fetch the table rows
after each click etc.
I cannot even think a reason why this would not work. Any opinions?
Upvotes: 1
Views: 450
Reputation: 6459
Try the following:
driver.execute_script("""
function button_visible(row) {
var opacity = row.style.opacity;
if (opacity == "" || opacity == 1) {
return true;
} else {
return false;
}
}
var table = document.querySelectorAll('div>.table');
for (x = 1; x < table.length; x++) {
row = table.item(x);
var row_buttons = row.querySelectorAll('icon-button');
for (var i = 0; i < row_buttons.length; i++) {
if (button_visible(row_buttons.item(i))) {
row_buttons.item(i).click();
}
}
}
""")
PS: For running multiline JS in Selenium (Python) should be used """
(start and end).
Hope it helps you!
Upvotes: 1