Send Images to WhatsApp Using Selenium & VBA - vba

Could you help me in my question, please?
I use Excel VBA & selenium to send WhatsApp messages to multiple contacts. I need to send images using copy & paste, but when I use (driver.SendKeys keys.Control, "v") ,A message appears"1 image you tried adding has no content".
Note1: Image is a link to an excel table.
Note2:I don`t like using the VBA command,(application.sendkeys "^v",true) because :
-It requires me to leave the pc until the code finishes, and it may take long time because messages are a lot.
-It can mistake because it requires WhatsApp window to be active.
public driver as new webdriver
Sub Whatsapp_new()
Dim keys As New Selenium.keys
Dim FindBy As New Selenium.By
'==============================================================
'start chrome
driver.SetProfile Environ("LOCALAPPDATA") & "\Google/Chrome\User Data"
driver.AddArgument "profile-directory=Default"
driver.Start "chrome"
driver.Window.Maximize
driver.Wait (1000)
driver.Get "https://web.whatsapp.com"
'==============================================================
'wait whatsapp to load
Do Until driver.IsElementPresent(FindBy.XPath("//div[#title='Search input textbox']"))
DoEvents
Loop
'==============================================================
'copy picture from sheet
for i = 1 to 100
range("a1")= i
ActiveSheet.Shapes("Picture 1").Select
Selection.Copy
phone_number =range("b2").value
'send message and picture
driver.Get "https://web.whatsapp.com/send?phone=" & phone_number & "?I=pt_br&text=how are you today"
driver.Wait 1000
driver.FindElementByXPath("//div[#title='Type a message']", 3000).SendKeys keys.Enter
driver.Wait 1000
driver.SendKeys keys.Control, "v"
driver.Wait 1000
driver.SendKeys keys.Enter
driver.Wait 1000
next
End Sub
Please help me
Thanks in advance

in python
driver.find_element(By.CSS_SELECTOR, '[data-testid="clip"]').click()
driver.find_element(By.CSS_SELECTOR, '[data-testid="attach-image"]+input').send_keys("your_link")
in Excel VBA
driver.FindElementByCss("[data-testid="clip"]").Click
driver.Wait 1000
driver.FindElementByCss("[data-testid="attach-image"]+input").SendKeys("your_link")

Related

VBA- wanted to click element which has multiple frames

With the previous question's answer I stepped ahead however still stuck on one point where I wanted to click the element but it seems it has 2 frames and thats the reason when I am running code its giving error that element not found, please check attachment and below code and advise.
Sub activeBexIE_Final()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'On Error Resume Next
Dim Perm_bot As New Selenium.IEDriver
Perm_bot.Get "official link"
Perm_bot.Wait 2000
Perm_bot.FindElementById("logonuidfield").SendKeys "XYZ"
Perm_bot.SendKeys Perm_bot.Keys.Tab
Perm_bot.SendKeys "PQR"
Perm_bot.SendKeys Perm_bot.Keys.Enter
Perm_bot.Wait 40000
Perm_bot.switchToFrame
Perm_bot.FindElementById("iframe_Roundtrip_9223372036563636042")
Perm_bot.FindElementById("BUTTON_OPEN_SAVE_btn1_acButton").SendKeys
Perm_bot.Keys.Enter
Perm_bot.Wait 30000' *till here I am sucessful- Opening Url-login-click on
"Open" option*
*'from here I am unable to move further, pls check attachment"select
layout" like how I wanted to select and also check the attachment "frame"
and "element" which is having the HTML details, not sure if this particular
element has 2 element, if yes then how I should write the script and after
this I wanted to do tab 7 times and then enter, kindly help for further
script, thanks in advance
'Perm_bot.switchToFrame Perm_bot.FindElementById("urPopupOuter0")
Perm_bot.switchToFrame Perm_bot.FindElementById("urPopupInner0")
Perm_bot.FindElementById("LOAD_state_tigen4_tlv1_list_unid6_tv").Click
SendKeys "{TAB}"
SendKeys "{TAB}"
SendKeys "{TAB}"
SendKeys "{TAB}"
SendKeys "{TAB}"
SendKeys "{TAB}"
SendKeys "{TAB}"
SendKeys "{ENTER}"
Perm_bot.Wait 10000
Application.DisplayAlerts = True
Application.ScreenUpdating = True
'perm_dot.Quit
'Set perm_dot = Nothing
End Sub
Select Layout
FrameElement
I believe your concern is your iframes are having similar attributes and you have to switch to each one of it before tabing 7 times.
Approach would be
Just like getting all windows handles and then loop you can use common xpath for iframe for e.g
findelements(By.Xpath("//iframes))
this will return iframe elements and then you can use loop and traverse and use
SwitchToFrame().
If your webpage is containing multiple frames and you need to perform an action on each frame too then I suggest trying to create an object for those frames and assign it to the 'document' object and then try to perform the action on each frame.
Sub demo()
Dim URL As String
Dim IE, doc1, doc2 As Object
Dim frame1 As HTMLFrameElement
Dim frame2 As HTMLFrameElement
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
URL = "D:\Tests\parent.html"
IE.Navigate URL
Do While IE.ReadyState = 4: DoEvents: Loop 'Do While
Do Until IE.ReadyState = 4: DoEvents: Loop 'Do Until
Set frame1 = IE.document.getElementByID("urpopupouter0")
Set frame2 = IE.document.getElementByID("urpopupinner0")
Set doc1 = frame1.contentWindow.document
Set doc2 = frame2.contentWindow.document
IE.document.getElementByID("btn1").Click
doc1.getElementByID("btn1").Click
doc2.getElementByID("btn1").Click
Set IE = Nothing
End Sub
I tested the above code on my side and it works fine with the multiple frames on a webpage.
Test result:
VBA code is clicking the button on each frame and on the parent web page which changes the forecolor of the button to red.
Further, you can try to modify the code as per your own requirements.

IE VBA open web page equal to clicking on first web page link

I'm trying to automate filling in a transaction on a series of web pages using Internet Explorer and MS-Access VBA. I've done quite a bit of this, but am stumped on this one pair of pages. I using code like this:
Set htmlDoc = ie.Document
With htmlDoc
Set e = .getElementById("j_idt31_data")
If e Is Nothing Then GoTo FileAppeal_Error
Set elems = e.getElementsByClassName("ui-widget-content ui-datatable-odd ui-datatable-selectable")
For Each e In elems
If InStr(1, e.innerText, "Evans ") > 0 Then
e.Click
Exit For
End If
Next
End with
I start on this page:
https://boe.shelbycountytn.gov/eFile/taxrep.xhtml,
click on one of the radio buttons on the left, then click on [Submit], which takes me to
https://boe.shelbycountytn.gov/eFile/search.xhtml
But I can't figure out how to programmatically get the [Submit] button to succeed. When I programmatically click on it I get a "Tax Rep is Required" error message.
Suggestions greatly appreciated.
I did this using selenium basic. Download then add the selenium type library reference.
Option Explicit
Public Sub test()
With New ChromeDriver
.Start "Chrome"
.Get "https://boe.shelbycountytn.gov/eFile/taxrep.xhtml"
.FindElementByCss("span.ui-radiobutton-icon.ui-icon.ui-icon-blank").Click
.FindElementByCss("span.ui-button-text.ui-c").Click
'other code
Stop
.Quit
End With
End Sub
Dim elems As MSHTML.IHTMLElementCollection, i As MSHTML.HTMLInputElement
Set elems = HTMLDocument.getElementsByClassName("ui-icon-blank")
Set i = elems(1) 'this gets the second option in the list
i.Click

vba code to find img title from webpage to excel using selenium vba

I am trying to find img title from webpage to excel using selenium vba below is the vba code which i am using but not getting any result and also below are the image of banks whose data i want in excel sheet.
Request you to please help me.
Sub Class_Initialize()
Set driver = CreateObject("Selenium.FirefoxDriver")
driver.get "https://www.99acres.com/supertech-cape-town-sector-74-noida-npxid-r922?sid=UiB8IFFTIHwgUyB8IzMxIyAgfCAxIHwgNyM0MyMgfCA4MjEyIHwjNSMgIHwg"
driver.Window.Maximize
Dim dd As Variant
dd = driver.findElementByClass("bankBodr bankTuple").Text
Range("A1") = dd
End Sub
Try this. It will lead you to fetch the content. Turn out that the items you are after are not visible until you scroll the browser downward. So I've used a javascript code to let the browser scroll to the bottom so that the items can be visualized.
Sub Get_Titles()
Dim post As Object
With CreateObject("Selenium.ChromeDriver")
.get "https://www.99acres.com/supertech-cape-town-sector-74-noida-npxid-r922?sid=UiB8IFFTIHwgUyB8IzMxIyAgfCAxIHwgNyM0MyMgfCA4MjEyIHwjNSMgIHwg"
.ExecuteScript ("window.scrollTo(0, document.body.scrollHeight);")
.Wait 500
For Each post In .FindElementsByCss("#carousel img")
r = r + 1: Cells(r, 1) = post.Attribute("title")
Next post
.Quit
End With
End Sub
Output:
LIC Housing Finance Ltd.
AXIS Bank LTD.
IDBI Bank Ltd.
Corporation Bank
HDFC home loans
Btw, change the portion within CreateObject("") to fit for your driver.

How do I enable stapler when printing?

I'm trying to print a word document from excel.
This works except I need to enable the stapler for this print job.
My printer, a Xerox workcentre 5755, can put one or two staples in the top left corner.
Excel apparently can manage this, I do NOT need to go into printer driver properties to enable the stapling, I can enable that directly from File-Print page.
When I go to this page, below "Settings" there is a dropdown written "No Staples" with a stapler symbol.
If I click that, I get choice of "No Staples", "Staple Top Left" and "Two Staples on Top Left" as well as other choices that are greyed out.
I tried recording a macro to print with staple top left and duplex printing.
This is what it gave me.
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
IgnorePrintAreas:=False
This does neither stapling nor duplex printing.
I read multiple threads on the subject but they are all old and don't really answer the question since in all cases the asker needed to change driver settings in properties so that is not my case. I have a printer that exposes the stapler function to excel.
Still I had to resort to one of the answers I found and that is to use sendkeys, which is highly unreliable.
Here is what my code looks like.
Sub PrintChecklist()
Dim myprinter As String
Dim PrintersList() As String
Dim printer_name As String
Dim x As Long
Dim wordapp As Word.Application
Dim CBC As CommandBarControl
Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open "C:\Users\XXXXX\Desktop\pool3.doc"
wordapp.Visible = True
myprinter = Application.ActivePrinter
wordapp.WindowState = wdWindowStateMaximize
PrintersList() = GetPrinterFullNames
For x = 1 To UBound(PrintersList)
If InStr(1, PrintersList(x), "MYPRINTERNAME", vbTextCompare) > 0 Then _
printer_name = PrintersList(x)
Next x
wordapp.ActivePrinter = printer_name
DoEvents
wordapp.Application.Activate
' only works in only one word opened
Dim lRet As Long
lRet = FindWindow("OpusApp", vbNullString)
SetForegroundWindow lRet
On Error Resume Next
Set CBC = Application.VBE.CommandBars.FindControl(ID:=752)
On Error GoTo 0
If Not CBC Is Nothing Then
CBC.Execute
DoEvents
'~~> File --> Print
SendKeys "%fp"
Sleep 3000
SendKeys "k"
Sleep 100
SendKeys "{DOWN}"
Sleep 100
SendKeys "~"
Sleep 100
SendKeys "%fp"
Sleep 100
Sleep 1000
SendKeys "s"
SendKeys "3-5,1-2"
SendKeys "%fp"
Sleep 1000
SendKeys "d"
SendKeys "{DOWN}"
SendKeys "~"
SendKeys "%fp"
Sleep 2000
SendKeys "p"
SendKeys "{NUMLOCK}"
End If
Sleep 5000
wordapp.ActivePrinter = myprinter
wordapp.Quit SaveChanges:=wdDoNotSaveChanges
End Sub
It works but if there is a delay or if the user touches anything in that 10 second span, then it all goes wrong very quickly.
Any advice welcomed !
Since this has gotten attention but no official answer, here is how I have dealt with this.
My printer is a network printer, so I have added it a second time to my computer under a different name. I set the default for that printer to be "with top left staple"
Now if I want to print with a staple, I print to that printer name instead of the other.
A bit quirky but it works reliably

IWebBrowser2::Navigate2 occasionally freezes when opening several new tabs

I'm writing an Excel script to open a list of PDFs in Internet Explorer tabs. It works fine most of the time, but occasionally when I try to close my browser window, a few of the tabs will close, then it stops and all IE instances will freeze, so I have to kill them all in Task Manager. Note that I can avoid the problem by closing each tab individually.
I'm running IE8 and Excel 2007, for the record. Here's my code:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
ShowBrowserWarning
Dim TheHTML As String, PDFs, PDF, First, SerialValue, Test, k
If Target.Column = 1 And Target.Count = 1 Then
' Get the serial number from the adjacent column
SerialValue = Cells(Target.Row, Target.Column + 1)
TheHTML = ShowHTML("http://ucmwww.dnr.state.la.us/ucmsearch/findAllDocuments.aspx?brief=False&query=xwellserialnumber+LIKE+'" & SerialValue & "'+AND+xdocumenttype+LIKE+'WELL ENGINEERING/MECHANICAL'&format=HTML&sortfield=xdate")
Set PDFs = ExtractPDFs(TheHTML)
If PDFs Is Nothing Then
MsgBox "No associated well engineering/mechanical PDFs."
Else
First = True
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
For Each PDF In PDFs
'While ie.Busy
' Dim testvar
' testvar = 1 + 1
'Wend
If First Then
' Open new IE window
ie.Navigate2 PDF.Value
First = False
Else
' Open tab in existing IE window
ie.Navigate2 PDF.Value, 2048
End If
Next
End If
End If
End Sub
What gives? Why does it freeze like that? Does it have anything to do this issue? (Please try not to laugh at my ignorance!) Any help is much appreciated.
Edit: see the italicized text above. I didn't quite describe the problem accurately!
And what about Browser-Busy check? Could it help to avoid the issue?
For Each PDF In PDFs
While ie.Busy
DoEvents
Wend
If First Then
' Open new IE window
ie.Navigate2 PDF.Value
First = False
Else
' Open tab in existing IE window
ie.Navigate2 PDF.Value, 2048
End If
Next
Or just wait between the browser.Navigate calls for a while to give the browser enough time to load one dokument before starting to load next one. Try different time-periods and watch if the freezing issue could be avoided this way.
For Each PDF In PDFs
DoEventsForTimePeriod timePeriodInSeconds:=15 ' try different time periods here
If First Then
' Open new IE window
ie.Navigate2 PDF.Value
First = False
Else
' Open tab in existing IE window
ie.Navigate2 PDF.Value, 2048
End If
Next
Private Sub DoEventsForTimePeriod(ByVal timePeriodInSeconds As Single)
' VBA.Timer: Returns a Single representing the number of seconds elapsed since midnight.
Dim pause As Single: pause = VBA.Timer + timePeriodInSeconds
Do While VBA.Timer < pause
DoEvents ' Yield to other processes.
Loop
End Sub
Well, I´m new too but, as far as can see, I would set ie = Nothing at the end of the sub to loose any relation between VBA and InternetExplorer Application