How to click on selection options using PhantomJS

There is a testkrok.org.ua page with a sequential selection of parameters. So, I need to create a series of 5 clicks on each of the options from 5 selection fields, which depend on each other.

document.querySelector('select.se1')[3] document.querySelector('select.se2')[1] document.querySelector('select.se3')[1] document.querySelector('select.se4')[1] document.querySelector('select.se5')[3] 

to redirect to the test page.

But if the picture is taken after the first click, the second panel does not appear? Maybe I didn’t hit the item?

 var page = require('webpage').create(); page.open('https://testkrok.org.ua', function(status) { console.log("Status: " + status); if(status === "success") { page.evaluate(function() { var theEvent = document.createEvent("MouseEvent"); theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); var element = document.querySelector('select.se1')[3]; element.dispatchEvent(theEvent); }); } setTimeout( function() { page.render('snapshot.png'); phantom.exit() }, 5000); }); 
+5
source share
1 answer

You cannot click (trigger a click event) in the options of the selection window. You need to change the selected option and then fire the change event . For instance:

 var sel = document.querySelector('select.se1'); sel.selectedIndex = 2; var event = new UIEvent("change", { "view": window, "bubbles": true, "cancelable": true }); sel.dispatchEvent(event); 

You can pack it into a function

 function selectOption(selector, optionIndex) { page.evaluate(function(selector, optionIndex){ var sel = document.querySelector(selector); sel.selectedIndex = optionIndex; var event = new UIEvent("change", { "view": window, "bubbles": true, "cancelable": true }); sel.dispatchEvent(event); }, selector, optionIndex); } 

Then you can call it one by one

 selectOption("select.se1", 2); selectOption("select.se2", 0); selectOption("select.se3", 0); ... 

You get the idea. In case the onChange event in the selection field needs remote data, for example, via AJAX, you will need to wait between calls. Use either a static wait time (see the following example) or use waitFor() .

 setTimeout(function(){ selectOption("select.se1", 2); }, 1000); setTimeout(function(){ selectOption("select.se2", 0); }, 2000); setTimeout(function(){ selectOption("select.se3", 0); }, 3000); ... 
+6
source

Source: https://habr.com/ru/post/1232222/


All Articles