I’m using SeleniumBasic (a fork of Selenium for VBA) in Excel to programmatically update a field on an internal website at my work for around 200 accounts per day. The field I’m updating is an input element and there must be an event listener or something that requires the element to be clicked before dispatching an event or whatever to signal a change was made.
For example, if I run a script like document.getElementById("myElement").value = 1 to update the value for the field and then run another script to click the save button, the page will discard the value I entered and revert it back to the previous value and no change is made.
However, if the input field is clicked (just clicking in the field and nothing else) before running the script to click the save button the change is kept and the update is successful.
I use SeleniumBasic’s Click() method to click [activate] the input element because I cannot figure out how to do this in JavaScript. Here’s the code I use to make the updates:
Ln 1 driver.ExecuteScript "document.getElementById("myElement").value = 1"
Ln 2 driver.findElementById("myElement").Click
Ln 3 driver.ExecuteScript "document.getElementById("saveButton").click()
My question is how do you focus an element when you’re web scraping?
Here’s something I created for troubleshooting, but still can’t seem to figure it out. I spent hours trying different things and searching online. Maybe I just don’t understand how things work, but SeleniumBasic’s Click() method does exactly what I want, so this has to be possible just writing some JavaScript, right?
<body>
<div>input 1<input id='foo' type='text' value='foo'></div>
<div>input 2<input id='bar' type='text' value='bar'></div>
<div>button<button id='btn' type='button'>my button</button></div>
<script>
document.querySelector("#btn").addEventListener('click', function() {
let input = document.querySelector("#bar");
input.focus();
console.log(Date());
});
</script>
</body>
If I manually click the button the console will output the datetime and the input 2 element is focused (cursor is inside the element). However, in the console if I execute document.querySelector("#btn").click(), the datetime is output but the element isn’t focused [clicked] like it would be when I manually click the button. I’ve tried writing events for dispatching and I get the same result. Hope this makes sense and it’s something simple I’m missing.