How to click on element within iframe? - vba

I’m trying to do web automation on IE using Selenium library.
Elements I want to click have iframes.
However, I’m getting the “element not found” error.
I tried many different approaches.
Sub activeBexIE_Final()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim Perm_bot As New Selenium.IEDriver
Perm_bot.Get "https://nalcodirect.nalco.com/irj/servlet/prt/portal/prtroot/pcd%213aportal_content%212fcom.sap.pct%212fplatform_add_ons%212fcom.sap.ip.bi%212fiViews%212fcom.sap.ip.bi.bex?BOOKMARK=0O867HQNBT13YLB5Q21HLAL2H", timeout:=1000, Raise:=False
Perm_bot.Wait 5000
' website opening successfully
Perm_bot.FindElementById("logonuidfield").SendKeys "XYZ#ABC.com"
Perm_bot.SendKeys Perm_bot.Keys.Tab
Perm_bot.SendKeys "ABCD"
Perm_bot.SendKeys Perm_bot.Keys.Enter
' the error is element not found at .click line
Perm_bot.switchToFrame Perm_bot.FindElementByName("iframe_Roundtrip_9223372036563636042")
Perm_bot.FindElementById("BUTTON_OPEN_SAVE_btn1_acButton").Click
Perm_bot.Wait 5000
Application.DisplayAlerts = True
Application.ScreenUpdating = True
perm_dot.Quit
Set perm_dot = Nothing
End Sub
HTML:
Iframe Screenshot:
Element Screenshot:

It might because the script runs faster than the page load. You could add a wait before switch to the iframe. Besides, there might be other elements with name iframe_Roundtrip_9223372036563636042 so you could use FindElementById when searching the iframe.
I made a simple sample with code below and it can work well:
Public Sub seleniumtutorial()
Dim driver As New Selenium.IEDriver
driver.Get "https://zhouyuzy.github.io/create-test-page/iframe.html "
driver.Wait 5000
driver.SwitchToFrame driver.FindElementById("iframe_Roundtrip_9223372036563636042")
driver.FindElementById("BUTTON_OPEN_SAVE_btn1_acButton").Click
driver.Wait 5000
End Sub
The result is like below:

Related

How to check the visibility of the element in Edge Browser using VBA Selenium and alternative to Obj.Wait

Unable to check the visibility of the element. Please guide
At present using Obj.Wait to wait so that Site is loaded fully. Is there any other way which can check the Edge Browser has loaded fully before execution of next code
In the instant case
Obj.Wait 580000
If Obj.IsElementPresent(By.XPath("//*[#id='downloadReport']/div")) = True Then
I have a following VBA code + Selenium which is opening a website, populate data from Excel and displays the record.
Dim Obj As New WebDriver
Sub EdgeAutoSF1CRA0()
Set Obj = New Selenium.EdgeDriver
Dim By As New Selenium.By
Obj.SetCapability "ms:edgeOptions", "{""excludeSwitches"":[""enable-automation""]}"
Obj.Start "edge", ""
Obj.Get "https://************
Obj.Window.Maximize
Obj.FindElementByName("croreAccount").SendKeys ("Search")
Obj.FindElementByXPath("//*[#id='loadSuitFiledDataSearchAction']/div[1]/div[3]/div[4]/img").Click
Obj.FindElementById("borrowerName").SendKeys (ThisWorkbook.Sheets("Sheet1").Range("C5").Value)
Obj.FindElementByXPath("//*[#id='search-button']/ul/li[1]/div/input").Click
Obj.Wait 580000
If Obj.IsElementPresent(By.XPath("//*[#id='downloadReport']/div")) = True Then
Obj.FindElementByXPath("//*[#id='downloadReport']/div").Click
Else
Obj.FindElementByXPath("//*[#id='three-icons']/ul/li[3]/a/div").Click
End If
'Call EdgeAutoSF25LA0
End Sub
If match is found, then element
XPath("//*[#id='downloadReport']/div")
is visible. The code at site is
'a href="downloadStatusReport" id="downloadReport">Download</a
If no match is found, then element
XPath("//*[#id='downloadReport']/div")
is not visible. The code at site is
'a href="downloadStatusReport" id="downloadReport" style="display: none;">Download</a

Trouble clicking on a load more button using vba

I'm trying to click on the Load More button located at the bottom of the left window of this webpage using vba in combination with selenium but the script always throws timeout error pointing at this .Get Url line. Although it seems I've defined an accurate xpath to locate the element, I can't think further as to what I should do now to achieve the same.
How can I click on that Load More button?
Sub ClickOnLoadMore()
Const Url$ = "http://www.ratemyprofessors.com/search.jsp?queryoption=TEACHER&queryBy=schoolDetails&schoolID=457&schoolName=James+Madison+University&dept=select"
Dim driver As New ChromeDriver, post As Object
With driver
.Get Url
Set post = .FindElementByXPath("//div[contains(.,'Load More')]")
.ExecuteScript "arguments[0].scrollIntoView();", post
post.Click
End With
End Sub
I see two "Load More" buttons. Both are matched by "//div[contains(.,'Load More')]". The first one is hidden. You need to handle second one.
Try this XPath
"//div[#class='content' and . = 'Load More']"
At least for me there were a couple of banners to dismiss as well as scrolling. There was no problem with the get line
Option Explicit
Public Sub ClickOnLoadMore()
Const Url$ = "http://www.ratemyprofessors.com/search.jsp?queryoption=TEACHER&queryBy=schoolDetails&schoolID=457&schoolName=James+Madison+University&dept=select"
Dim driver As New ChromeDriver, post As Object
With driver
.get Url
If .FindElementsByCss(".close-notice.close-this").Count > 0 Then
.FindElementByCss(".close-notice.close-this").Click
End If
.SwitchToFrame .FindElementByCss("[id^='spout-unit-iframe']")
With .FindElementByCss("#spout-ads #spout-header-close")
.ScrollIntoView
.Click
End With
.SwitchToDefaultContent
.ExecuteScript "document.querySelector('.result-list [onclick*=LoadMore]').scrollIntoView(true);" & _
"window.scrollBy(0, -(window.innerHeight - this.clientHeight) / 2);"
.FindElementByCss(".result-list [onclick*=LoadMore]").Click
Stop '<== Delete me later
'other code
.Quit
End With
End Sub

How to click the date picker selenium VBA?

I'd like to use selenium VBA to download some data from Yahoo Finance KOSPI COmposite Index.
I got the difficulty when click the date picker arrow to get the mini window to select the end date as today. I tried to record the marco through selenium IDE in chrome, but IDE does not record the step when I click the arrow of the Time period to get the date picker visible.
Below is my code in VBA.
Public Function seleniumKorea(bot As WebDriver)
Dim url As String
url = "https://finance.yahoo.com/quote/%5EKS11/history?period1=1484018309&period2=1515554309&interval=1d&filter=history&frequency=1d"
bot.Start "chrome", url
bot.Get "/"
'Not sure how to add date picker here
bot.FindElementByName("endDate").Clear
bot.FindElementByName("endDate").SendKeys (Date)
bot.FindElementByXPath("(.//*[normalize-space(text()) and normalize-space(.)='End Date'])[1]/following::button[1]").Click
Application.Wait (Now + TimeValue("0:01:00"))
bot.FindElementByXPath("(.//*[normalize-space(text()) and normalize-space(.)='As of'])[1]/following::div[4]").Click
Application.Wait (Now + TimeValue("0:01:00"))
bot.FindElementByXPath("(.//*[normalize-space(text()) and normalize-space(.)='Currency in KRW'])[1]/following::span[2]").Click
Application.Wait (Now + TimeValue("0:01:00"))
End Function
I tried to use the ByXPath to get the svg class but failed.
Thanks in advance.
I would use the following which submits the OATH consent if required and scrolls the date picker into the viewport
Option Explicit
Public Sub DatePicking()
Dim d As WebDriver
Set d = New ChromeDriver
Const URL = "https://finance.yahoo.com/quote/%5EKS11/history?period1=1484018309&period2=1515554309&interval=1d&filter=history&frequency=1d/"
With d
.get URL
If .Title = "Yahoo is now part of Oath" Then
.FindElementByCss("form").submit
End If
With .FindElementByCss("[data-test='date-picker-full-range']")
.ScrollIntoView
.Click
End With
With .FindElementByCss("[name=startDate]")
.Clear
.SendKeys "05/10/2017"
End With
With .FindElementByCss("[name=endDate]")
.Clear
.SendKeys "05/10/2017"
End With
Stop '<==Delete me later
.Quit
End With
End Sub
Check this out. It should serve the purpose. I used xpath to solve the issue.
Sub CustomizeDate()
Const Url$ = "https://finance.yahoo.com/quote/%5EKS11/history?period1=1484018309&period2=1515554309&interval=1d&filter=history&frequency=1d"
Dim driver As New ChromeDriver
With driver
.get Url
.FindElementByXPath("//input[#data-test='date-picker-full-range']", timeout:=5000).Click
.FindElementByXPath("//input[#name='startDate']").Clear.SendKeys ("01/05/2017")
.FindElementByXPath("//input[#name='endDate']").Clear.SendKeys ("01/08/2017")
.FindElementByXPath("//button/span[.='Done']", timeout:=5000).Click
.FindElementByXPath("//button/span[.='Apply']", timeout:=5000).Click
End With
End Sub
Don't use hardcoded delay for any item to appear. Use Explicit Wait instead. The script will wait upto 5000, meaning 5 seconds for that item to be available.

Cannot Login with Excel VBA Selenium

So I am tryin to create a Script that will automatically login for me on this website:
https://teespring.com/login
This is my script so far:
Sub openBrowser()
'Open new browser
Set driver = New Selenium.ChromeDriver
'Navigate to Website
urlWebsite = "https://teespring.com/login"
driver.Get urlWebsite
So I have tried to enter my username with the following lines of code:
driver.FindElementByCss("").sendKeys Username
But I got an error saying element not visible
Is there any way I can still automate the login process?
thanks for your help and if you need further information I will try my best to as I am still learning how to handle vba selenium :-)
It is not visible because it is inside a form.
You need to access via form:
Option Explicit
Public Sub EnterInfo()
Dim d As WebDriver
Set d = New ChromeDriver
Const URL = "https://teespring.com/login"
With d
.Start "Chrome"
.get URL
With .FindElementByClass("js-email-login-form")
.FindElementByCss("input[name=email]").SendKeys "myEmail"
.FindElementByCss("input[name=password]").SendKeys "myPassWord"
.FindElementByCss("input[type=submit]").Click
End With
Stop '<== Delete me after inspection
.Quit
End With
End Sub

VBA-Excel: Filling forms in an IE Window

I'm hoping someone can help. I'm trying to speed up the process of filling a webform that must be completed dozens or hundreds of times with information stored in excel.
To do this, I need one button to open an IE window and navigate to a certain website's login page (I've figured this bit out). The user can then log in and navigate to the form that needs to be filled. Then, I'd like the user to be able to return to the excel page, click another button, which will automatically fill several drop downs and text boxes.
Within Excel, I already have some code to allow the user to search for the particular set of information that needs to go to the form, so all they should have to do is click the button to transfer it over. The first bit of the code is just this:
Public IE As Object
Public Sub OpenIE()
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "loginpage url"
End Sub
Where I'm having trouble, however, is having a different function access the same IE window once the user has logged in and navigated to the form. Right now I've got this:
Sub FillMacro()
Dim sh As Object, oWin As Object
Set sh = CreateObject("Shell.Application")
For Each oWin In sh.Windows
If TypeName(oWin.document) = "HTMLDocument" Then
Set IE = oWin
Exit For
End If
Next
IE.Visible = True
Application.Wait (Now + TimeValue("00:00:01"))
IE.document.getElementById("idec").Value = "John"
Application.Wait (Now + TimeValue("00:00:01"))
IE.document.getElementById("idee").Value = "Smith"
End Sub
Most of that I've gotten from other posts on this forum, and while I'm a bit of a novice at this, the problem seems to be that for some reason VBA can't find the text boxes with the id of LastName or FirstName. What's more, the IE.Visible = True doesn't bring the IE window back to the foreground, so I'm trying to find the proper line to do that. When I try to run the code, I get an "Object Required" error at:
IE.document.getElementById("idec").Value = "John"
I've tried searching this site and will continue to look, but any help in the meantime would be greatly appreciated!
On the Internet Explorer page, here is the line for the first text box I'm trying to fill:
<input name="componentListPanel:componentListView:1:component:patientLastNameContainer:patientLastName" class="input300" id="idec" type="text" maxlength="60" value="">
Why not automate logging process as well? Login could be stored in Excel and its value read by macro from cell.
As Tim Williams suggests, if there is Iframe on website, use (for me it works only with contentwindow included):
IE.document.getElementById("iFrameIdHere").contentwindow.document.getEleme‌ntById("idec").Value = "John"
Instead of Application.Wait use:
Do Until IE.ReadyState = 4 And IE.Busy = False
DoEvents
Loop
It will save you a lot of time when page loads fast and prevent errors when loading exceeds wait time. Use it ONLY after page reloads (meaning after navigating or anything what causes page reloads, especially .click on HTML elements.
Use early binding, it's a bit faster than creating objects. It can increase performance by a few percent based on page loading speed, the faster pages load, the bigger increase.
Set IE = New InternetExplorer
Finally, you can toggle loading pictures, depending on whether you need to download images from website.
Public Sub ShowPictures(ByVal EnabledStatus As Boolean)
Public ScrapingCancelled as Boolean
Dim obj_Shell
Dim v_Result As Variant
Set obj_Shell = CreateObject("WScript.Shell")
'Reads the registry key that determines whether 'Show pictures' Internet Explorer advanced setting is enabled
v_Result = obj_Shell.RegRead("HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\Display Inline Images")
Select Case v_Result
Case "yes" 'Pictures are displayed
If EnabledStatus = False Then _
obj_Shell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\Display Inline Images", "no", "REG_SZ"
Case "no" 'Pictures are not displayed
If EnabledStatus = True Then _
obj_Shell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\Display Inline Images", "yes", "REG_SZ"
Case Else
ScrapingCancelled = True
End Select
End Sub
No images loaded:
ShowPictures (0)
Images loaded:
ShowPictures (1)
A good practice is to set value to 1 in the end of macro.