Fill in internet explorer drop down box in form using com

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Fill in internet explorer drop down box in form using com

09 Jul 2017, 16:27

I am trying to select items from a dropdown menu on a javascript webpage. I want to fill in the menu value via a userform using VB. Relevant Web code source is below

Code: Select all

div class="sa-form-control sa-form-field" style="padding-bottom: 20px;"><select name="country" class="ui-textfield ui-textfield-system sa-country sa-error-field"><option selected="selected" value="">--Please Select--</option>
<option value="RU">Russian Federation</option>
<option value="US">United States</option>
<option value="ES">Spain</option>
<option value="FR">France</option>
option value="OTHER">Other Country</option>
<option value="">-------- Country & Territories (A-Z) --------</option></select>
<div class="sa-success-icon" style="display: none;"></div><p class="sa-error-tips" style="display: block;">Please select a Country/Region</p></div>
I have tried the following but not working

Code: Select all

oIE.document.getElementsByClassName("ui-textfield ")(0).Value = "RU"
Also this

Code: Select all

oIE.document.getElementsByName("country")(0).Value = "RU"
Also not working
Any help would be great
Thanx
A_AhkUser
Posts: 1147
Joined: 06 Mar 2017, 16:18
Location: France
Contact:

Re: Fill in internet explorer drop down box in form using com

09 Jul 2017, 16:43

.getElementByClassName method returns an array while array elements are retrieved using brackets (i.e. myArray[0]):

Code: Select all

oIE.document.getElementsByClassName("ui-textfield")[0].value := "RU"
alternatively, you can use .querySelector method:

Code: Select all

oIE.document.querySelector(".ui-textfield.ui-textfield-system.sa-country.sa-error-field").selectedIndex := 1 ; параметр querySelector наблюдает css синтаксу: точка - это класс.
my scripts
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Re: Fill in internet explorer drop down box in form using com

10 Jul 2017, 02:14

Thanx very much works great
I now need to left click the item in order to manually input a country not found in list

I tried the following but did not work

Code: Select all

oIE.document.getElementsByClassName("ui-textfield")[0].click()
Many thanx
Last edited by smbs on 10 Jul 2017, 07:06, edited 1 time in total.
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Re: Fill in internet explorer drop down box in form using com

12 Jul 2017, 05:37

Maybe I did make my requirement clear. Source code of web page as above.
On the form appears a drop down box to fill in country see http://imgur.com/a/yLt6v I want to click this box so a list of countries appears to choose from see http://imgur.com/a/wfvVz
My first request which was answered was to directly place the country into the drop box which works fine but an additional requirement is to be able to manually choose the country so I need to left click the box--how can I do this using com?
Many thanx -hope I have made myself clear!
A_AhkUser
Posts: 1147
Joined: 06 Mar 2017, 16:18
Location: France
Contact:

Re: Fill in internet explorer drop down box in form using com

12 Jul 2017, 11:02

smbs wrote:I want to click this box so a list of countries appears to choose from (...)--how can I do this using com?
If it is your own code you can modify it so that at the cost of some css tricks you could make it... otherwise you can not do this using com - as far as I know.
my scripts
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Re: Fill in internet explorer drop down box in form using com

12 Jul 2017, 13:36

@A_AhkUser!
Thanx for your answer-- ok I understand-- can you please show me a way to do it in whatever way it is possible!
Thanx for your patience
A_AhkUser
Posts: 1147
Joined: 06 Mar 2017, 16:18
Location: France
Contact:

Re: Fill in internet explorer drop down box in form using com

12 Jul 2017, 14:30

Hi smbs,

Maybe this could work:

Code: Select all

element := oIE.document.getElementsByClassName("ui-textfield")[0]
element.focus() ; focus the element
sendinput, {Down}
return
my scripts
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Re: Fill in internet explorer drop down box in form using com

12 Jul 2017, 15:57

Thanx for reply
The element gets focus and if I manually left click the mouse the list appears so I tried
mouseclick,left
mouseclick,left,,,,d
Neither worked.
Is there any way of moving the mouse to element in focus an then leftclicking?
Again many thanx
A_AhkUser
Posts: 1147
Joined: 06 Mar 2017, 16:18
Location: France
Contact:

Re: Fill in internet explorer drop down box in form using com

12 Jul 2017, 16:18

Actually there is but... as for me, I never managed to if only initialize a mouse event

Code: Select all

WB.document.createEvent("mousevent")
using com i order to simulate a mouse click... Maybe someone else know how to simply achieve this.

One solution could be to inject a custom interactive html displaying the dropdownlist option ; here's a basic example using the prompt function wich allows an user input while having all the options under your eyes. Although I wonder if it's worth it.

Code: Select all

Gui, 1:Add, ActiveX, vWB x1 y30 w598 h598, Shell.Explorer
WB.silent := true
WB.Navigate("http://www.wordreference.com/")
Loop {
sleep, 300
} Until (!WB.busy or WB.document.readyState == 4)
element := WB.document.getElementById("fSelect") ; matchs the language drop down list (select element) @wordreference.com for th example
Gui, 1:Show, w600 h600
ComObjConnect(element, new EventHandler) ; this connects the object's event source to the EventHandler object so that when an event is raised, the corresponding method is called.
return



!i::
element.click() ; click the dropdownlist (this will trigger the EventHandler.onclick method below)
return


Class EventHandler {

	onclick(__element) { ; the event target is automatically bound to the func
	global WB ; make WB object accessible from within the function where all variables are implicitly locals
	__str := "" ; an empty string
	Loop % (__a:=__element.getElementsByTagName("option")).length ; retrieves all options
		__str .= __a[ a_index - 1].value . "|" ; a list of all available option separeted by | as delimiter
	__element.value := WB.document.parentWindow.prompt(__str) ; set the dropdownlist value to be the user input
	}
	
}
my scripts
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Re: Fill in internet explorer drop down box in form using com

12 Jul 2017, 17:35

Thanx for reply--I give up! Custom html just ain't worth it as you say!
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Re: Fill in internet explorer drop down box in form using com

13 Jul 2017, 02:01

Thanx for js link --it looks slightly beyond my jscript capabilities which is close to zero!
I will try the the interactive html you suggested
sancarn
Posts: 224
Joined: 01 Mar 2016, 14:52

Re: Fill in internet explorer drop down box in form using com

13 Jul 2017, 02:58

Code: Select all

div class="sa-form-control sa-form-field" style="padding-bottom: 20px;"><select name="country" class="ui-textfield ui-textfield-system sa-country sa-error-field"><option selected="selected" value="">--Please Select--</option>
<option value="RU">Russian Federation</option>
<option value="US">United States</option>
<option value="ES">Spain</option>
<option value="FR">France</option>
option value="OTHER">Other Country</option>
<option value="">-------- Country & Territories (A-Z) --------</option></select>
<div class="sa-success-icon" style="display: none;"></div><p class="sa-error-tips" style="display: block;">Please select a Country/Region</p></div>
If this is someone else's website there is a high probability that they are using a form <form>...</form>. If this is the case you would be better making a HTTP GET/POST request instead of using JavaScript to fill the form. This way you can use all your AHK knowledge to make your own GUI and do the rest with HTTP requests.

HTTP requests are a lot more complex though, and you would be best using something like Google chrome to see the headers. Here's an example I used for automating this council website:

Code: Select all

function getMonthData(callback){
	httpPostAsync("https://pawam.gedling.gov.uk/online-applications/monthlyListResults.do?action=firstPage","searchCriteria.parish=&searchCriteria.ward=&month=Nov+16&dateType=DC_Validated&searchType=Application",function(txt){
		console.log("Getting 100 results per page...")
		httpPostAsync("https://pawam.gedling.gov.uk/online-applications/pagedSearchResults.do","searchCriteria.page=1&action=page&orderBy=DateReceived&orderByDirection=Descending&searchCriteria.resultsPerPage=100",function(txt){
			var docx = XMLDOM(txt)
			window.docx = docx
			var results = docx.getElementsByClassName("searchresult")
			window.results = results
			console.clear()
			console.log("Appending results to array...")
			for (var el of results){
				var elDescripter	= el.getElementsByTagName("a")[0]
				var elAddresser		= el.getElementsByClassName("address")[0]
				var elMetaInfo		= el.getElementsByClassName("metaInfo")[0]
				
				//Get info from elements
				var sDescription	= standardiseText(elDescripter.innerText)
				var sURL			= elDescripter.attributes[0].value
				var sAddress		= standardiseText(elAddresser.innerText)
				
				//Parse metadata
				var sMetadata 		= standardiseText(elMetaInfo.innerText)
				var RefNum			= standardiseText(sMetadata.match(/Ref. No: ([^|]+)/)[1])
				var DateReceived	= standardiseText(sMetadata.match(/Received: ([^|]+)/)[1])
				var DateValid		= standardiseText(sMetadata.match(/Validated: ([^|]+)/)[1])
				var Status			= standardiseText(sMetadata.match(/Status: (.+)/)[1])
				window.bigArray.push([sDescription,sAddress,RefNum,DateReceived,DateValid,Status,sURL].join(","))
			}
		});
	});
}




function standardiseText(s){
	s=s.replace(/\<.+?\>/g,"")		//replace all html tags with blank
	s=s.replace(/\s+/g," ")			//replace all \s+ with space
	return s.trim()
}

function XMLDOM(xml){
	var parser = new DOMParser();
	var xmlDoc = parser.parseFromString(xml,"text/html")
	return xmlDoc
}

function httpPostAsync(url,params,callback){
	//Get data by posting a http request
	//Example:
	//	url = "get_data.php";
	//	params = {lorem:"ipsum",name:"binny"} --> "lorem=ipsum&name=binny";
	var http = new XMLHttpRequest();

	http.open("POST", url, callback!=undefined);	//ask for callback only if defined
	
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	
	//Below are not required anymore. See: https://stackoverflow.com/questions/7210507/ajax-post-error-refused-to-set-unsafe-header-connection
	//http.setRequestHeader("Content-length", params.length);
	//http.setRequestHeader("Connection", "close");
	
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			if(callback!=undefined) callback(http.responseText);
		}
	}
	http.send(params);
}
There are also http request functions that you can use directly in AHK, but I have no experience with using it. However I would probably advise it unless you want to get used to callback hell
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Re: Fill in internet explorer drop down box in form using com

13 Jul 2017, 11:16

The site is from aliexpress.com I am trying to fill in the shipping address automatically with no user interaction.
sancarn
Posts: 224
Joined: 01 Mar 2016, 14:52

Re: Fill in internet explorer drop down box in form using com

13 Jul 2017, 13:32

smbs wrote:The site is from aliexpress.com I am trying to fill in the shipping address automatically with no user interaction.
Do you mean this thing?

https://puu.sh/wIJ8i/9c3d286124.png
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Re: Fill in internet explorer drop down box in form using com

13 Jul 2017, 15:24

sancarn!
No --I think you might have to register and then you will see a form to fill in a shipping address.
Registration is free. There are also some good finds!
sancarn
Posts: 224
Joined: 01 Mar 2016, 14:52

Re: Fill in internet explorer drop down box in form using com

13 Jul 2017, 17:21

smbs wrote:sancarn!
No --I think you might have to register and then you will see a form to fill in a shipping address.
Registration is free. There are also some good finds!
I think I found the site you were talking about. Try this javascript:

Code: Select all

document.querySelector('#page > div.email-div > div > input').value = "[email protected]"
document.querySelector('#address-main > div.sa-form > div:nth-child(3) > div > input').value="MyContactName"
document.querySelector('#address-main > div.sa-form > div:nth-child(4) > div > select').value="RU" //Russian Federation
document.querySelector('#address-main > div.sa-form > div:nth-child(5) > ul > li.sa-form-group.sa-form-field > input').value="My street address"
document.querySelector('#address-main > div.sa-form > div:nth-child(5) > ul > li:nth-child(2) > input').value="Apartment, suite, unit etc."
document.querySelector('#address-main > div.sa-form > div.row.sa-form-group.sa-province-group > div > select').value="Alabama"
document.querySelector('#address-main > div.sa-form > div.row.sa-form-group.sa-city-group > div > input').value="My city"
document.querySelector('#address-main > div.sa-form > div:nth-child(8) > div > input').value = "THEZIP10"
document.querySelector('#address-main > div.sa-form > div:nth-child(9) > ul > li > input.ui-textfield.ui-textfield-system.sa-country-code.js-input-field').value="+22"
document.querySelector('#address-main > div.sa-form > div:nth-child(9) > ul > li > input.ui-textfield.ui-textfield-system.sa-phone-number.js-input-field').value="0000000000"
document.querySelector('#address-main > div.sa-form > div:nth-child(14) > a.ui-button.ui-button-primary.ui-button-medium.sa-confirm').click()
I won't be buying from the site though :P I'm not one for buying... anything.

Note:

If you are doing this through the Shell.Explorer control in AHK you may need to implement document.querySelector yourself... If that is the case I would port the following javascript:

https://gist.github.com/chrisjlee/8960575

Either that, or remake what you are making on a custom browser using electron. Or if the tool is just for you, just put the javascript above as a Google Chrome snippet :)

Edit:

Finally, if you want a list of options you can use this JavaScript function:

Code: Select all

function getOptions(element){
	var options=[]
	if(element.tagName!="SELECT") return []
	o = element.options
	for(i in k){if(typeof(k[i])=="object") options.push(k[i].value)}
	return options
}
Used like getOptions(document.querySelector('#address-main > div.sa-form > div:nth-child(4) > div > select'))
A_AhkUser
Posts: 1147
Joined: 06 Mar 2017, 16:18
Location: France
Contact:

Re: Fill in internet explorer drop down box in form using com

13 Jul 2017, 18:33

smbs wrote:The site is from aliexpress.com I am trying to fill in the shipping address automatically with no user interaction.
smbs wrote:(...) is to be able to manually choose the country
This sentences manifestly contradict themselves... and now I understand: you wanted to drop out the dropdownlist because settle for setting the value did not trigger the mechanism as an user interaction does... Besides, why have you concealed it's about aliexpress? nobody will reproach you to make advertising :lol: - it's that, that way, one could be able to check what actually happen in the DOM when one clicks on an option and hence help you.

sancarn wrote:If you are doing this through the Shell.Explorer control in AHK you may need to implement document.querySelector yourself...

Actually, you can retrieve and use queryselector using execscript, it's really confusing for me... :crazy:

Code: Select all

#NoEnv
#Warn
#SingleInstance force

Gui, Add, ActiveX, vAXC w400 h400, Shell.Explorer
AXC.navigate("http://www.google.fr")
while (AXC.busy or AXC.readyState <> 4)
sleep, 100
Gui, Show, AutoSize
AXC.document.parentwindow.execScript("var replacement = { querySelector: function(__s) { return document.querySelector(__s); }};")
MsgBox % AXC.document.parentwindow.replacement.querySelector("#hplogo").outerHtml
my scripts
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Re: Fill in internet explorer drop down box in form using com

14 Jul 2017, 02:47

sancarn A_AhkUser
Thanx for your patience and replies---Your answers seem to be a bit beyond me! I am trying to understand what u are telling me.I have no experience with google chrome snippets trying to look it up and learn how to do it
A_AhkUser
Yes u are correct-- I didn't want to advertise. Sorry if I made a mistake!
You are correct --if country in not clicked you cannot fill in state (Usa and UK)
Your code using Shell.Exporer not sure how to implement this. If u have the patience pls clarify if not I will understand.
Once again guys many thanx for your help and patience!
smbs
Posts: 98
Joined: 27 Feb 2014, 11:07

Re: Fill in internet explorer drop down box in form using com

14 Jul 2017, 03:42

Sancarn
Ok got the snippet working but there is a problem as stated earlier- inputting country by snippet does not trigger the mechanism for inputting "state field" as user interaction does. For example setting country Uk "State/ province field" always gives error.
If I could always input "Other" which is last option in drop down list for "State field" it would be acceptable.
Is it possible using this snippet to input many addresses by using a loop--ie looping thru a file (exel/csv) containing addresses and inputting addresses one after the other to chrome snippet?
Using Ahk with Ie explorer I have almost managed to do it (of course with the help of A_AhkUser) although I still have the "State field" problem mentioned above.
Thanx again

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Google [Bot], RandomBoy and 258 guests