i have tried using google translate to translate names from language to another using c# and its working fine but now im trying to do the same thing using ms access vba i have tried so many ways but with no luck!
this is the code written in c# and its working fine
public string trans_arabic_to_english(string word)
{
var toLanguage = "en";//English
var fromLanguage = "ar";//Deutsch
var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={fromLanguage}&tl={toLanguage}&dt=t&q={HttpUtility.UrlEncode(word)}";
var webClient = new WebClient
{
Encoding = System.Text.Encoding.UTF8
};
var result = webClient.DownloadString(url);
try
{
result = result.Substring(4, result.IndexOf("\"", 4, StringComparison.Ordinal) - 4);
return result;
}
catch
{
return "Error";
}
}
this is the code in vba
Private Sub Command0_Click()
Dim toLan As String, fromLan As String, resp As String, s As String, a_name As String, url As String
toLang = "ar"
fromlang = "en"
a_name = "omar khalil"
url = "https://translate.googleapis.com/translate_a/single?"
url = url & "client=gtx&sl={""" & toLang & """}&tl={""" & fromlang & """}&dt=t&q={""" & a_name & """}"
url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
url = url & fromlang & "&tl=" & to_lang & "&dt=t&q=" & a_name
'==
Dim ob As Object
Set ob = CreateObject("WinHttp.WinHttpRequest.5.1")
ob.Open "POST", url, False
ob.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
ob.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
ob.Send
If ob.Status <> 200 Then
resp = ob.ResponseText
MsgBox resp
End Sub
i have tried using WinHttp also with no luck at all!
any one can help me with this issue Thanks .
Try the next function, please:
Private Function GTranslate(strInput As String, strFromLang As String, strToLang As String) As String
Dim strURL As String, objHTTP As Object, objHTML As Object, objDivs As Object, objDiv As Variant
strURL = "https://translate.google.com/m?hl=" & strFromLang & _
"&sl=" & strFromLang & _
"&tl=" & strToLang & _
"&ie=UTF-8&prev=_m&q=" & strInput
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.Open "GET", strURL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.Send ""
Set objHTML = CreateObject("htmlfile")
With objHTML
.Open
.Write objHTTP.responseText
.Close
End With
Set objDivs = objHTML.getElementsByTagName("div")
For Each objDiv In objDivs
'If objDiv.className = "t0" Then 'it does not work, anymore
If objDiv.className = "result-container" Then 'adapted on December 28th
GTranslate = objDiv.innerText: Exit For
End If
Next objDiv
Set objHTML = Nothing: Set objHTTP = Nothing
End Function
It can be called in the next way:
Sub testTranslateG()
MsgBox GTranslate("Este es un libro", "auto", "en")
End Sub
The second parameter can be "auto" (like in the testing Sub), or the specific language abbreviation if more accurate translation needed ("es" - Spanish, "ru" - Russian, "ro" - Romanian etc.).
In order to find the correct abbreviation, you can open Google Translate page, right click and choose 'View page source'. Then try finding some language. Let us say Spanish. In that area you will see a script having strings like the following one: "code:'it',name:'Italian'". Easy to understand that "it" is the abbreviation for Italian...
Related
I'm trying to download a file from this website, tried a bunch of code i can find and the file is downloaded but shows the html of the login page
Below are 2 versions that I tried. I tried every code snippet I could find on SO and have had no luck so far.
I tried both versions here, they had the same problem but their solution isn't working for me.
Vba download file from internet WinHttpReq with login not working
It seems like I'm not getting past the login process. I know that the variables (username, password) are wrong in the code below, but I did try every variable I can find in the source (UniqueUser, UniqueLogin, LoginName, every word they had there) and still no luck.
Some versions of the code error on the SET COOKIE line, others give no errors, the file is downloaded but it's still the html of the login page inside the file
Sub DownloadFile2(myURL As String)
Dim CurPath As String
CurPath = CurrentProject.Path & "\"
Dim strCookie As String, strResponse As String, _
strUrl As String
Dim xobj As Object
Dim WinHttpReq As Object
Set xobj = New WinHttp.WinHttpRequest
UN = "hhhhh"
PW = "gggg"
strUrl = "https://pnds.health.ny.gov/login"
xobj.Open "POST", strUrl, False
xobj.SetRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
xobj.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xobj.Send "username=" & UN & "&password=" & PW & "&login=login"
strResponse = xobj.ResponseText
strUrl = myURL
xobj.Open "GET", strUrl, False
xobj.SetRequestHeader "Connection", "keep-alive"
xobj.SetRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
xobj.Send
strCookie = xobj.GetResponseHeader("Set-Cookie")
strResponse = xobj.ResponseBody
If xobj.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write xobj.ResponseBody
oStream.SaveToFile CurPath & "ValidationDataHFIS.csv", 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
End If
End Sub
Sub ddd()
DownloadFile2 ("https://pnds.health.ny.gov/xxxx/xxxx/8")
End Sub
You are sending login details to an incorrect login address. Your correct login address is https://pnds.health.ny.gov/account/login the page expects LoginName and Token. The token is generated using SecurityManager.generate( u, p );
You can still consult with their IT Team to make sure you are not violating their policy.
Here is a way of doing it using a IE browser object.
Private Sub DownloadValidationData()
'Create Internet explorer object
Dim IE As Object
Set IE = CreateObject("INTERNETEXPLORER.APPLICATION")
IE.Visible = True
Dim URL As String: URL = "https://pnds.health.ny.gov/account/login"
IE.Navigate URL
While IE.READYSTATE <> READYSTATE_COMPLETE
DoEvents
Wend
Dim userName As String: userName = "test"
Dim password As String: password = "test"
'Fill the login form
IE.Document.getElementById("UniqueUser").Value = userName
IE.Document.getElementById("UniquePass").Value = password
'Submit the form
IE.Document.querySelector("button.SignIn").Click
'Wait for login to complete
While IE.READYSTATE <> READYSTATE_COMPLETE
DoEvents
Wend
'Verify you are logged in: As we don't know what the site looks like after login in. Only you can do this step.
'Navigate to Download Page. This should prompt to save the file.
IE.Navigate theDownloadUrl '"https://pnds.health.ny.gov/xxxx/xxxx/8"
'Once downloaded just close the browser and exit
'IE.Quit
'Set IE = Nothing
'If you are interested in geting/generating the token using their script you can play around with below lines. These lines come before loging in. Please note: execScript is depreciated now
'Dim Token as string
'IE.Document.parentwindow.execScript ("$('#Token').val(SecurityManager.generate(""" & username & """, """ & password & """ ))")
'Token = IE.Document.getElementById("Token").Value
'Use the token to sign in using your code. That'll be xobj.Send "LoginName =" & userName & "&Token=" & Token
'But not sure if it will work.
End Sub
I would make a little recursive function that checks for redirects until there are none left.
Like this:
Option Explicit
Const WinHttpRequestOption_EnableRedirects = 6
Public Function GetRedirect(ByRef oHttp As Object, ByVal strUrl As String) As String
With oHttp
.Open "HEAD", strUrl, False
.Send
End With
If oHttp.Status = 301 Or oHttp.Status = 302 Or oHttp.Status = 303 Then
GetRedirect= GetRedirect(oHttp, oHttp.GetResponseHeader("Location"))
Else
GetRedirect= strUrl
End If
End Function
Sub DownloadFile2(myURL As String)
Dim CurrentProject
Dim CurPath As String
CurPath = CurrentProject.Path & "\"
Dim strCookie As String, strResponse As String, _
strUrl As String
Dim xobj As Object
Dim WinHttpReq As Object
Set xobj = CreateObject("WINHTTP.WinHTTPRequest.5.1")
Dim UN As String
UN = "hhhhh"
Dim PW As String
PW = "gggg"
strUrl = "https://pnds.health.ny.gov/login"
With xobj
.Open "POST", strUrl, False
.SetRequestHeader "Connection", "keep-alive"
.SetRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.Send "&username=" & UN & "&password=" & PW & "&login=login"
End With
strUrl = GetRedirect(xobj, myURL)
If xobj.Status = 200 Then
Dim oStream As Object
Set oStream = CreateObject("ADODB.Stream")
With oStream
.Open
.Type = 1
.Write xobj.ResponseBody
.SaveToFile CurPath & "ValidationDataHFIS.csv", 2 ' 1 = no overwrite, 2 = overwrite
.Close
End With
End If
End Sub
Sub ddd()
DownloadFile2 ("https://pnds.health.ny.gov/xxxx/xxxx/8")
End Sub
NOTE: This code is untested and would need to be adapted for your use case.
I originally created a VBA macro that would uses IE automation to click specific form buttons on an ASPX page. The page has 5 form options you have to pass through.
drop down list for group
drop down list for location
Graphical calendar where you select the date
List box for area's
Generate Report button
I would like to move away from using the IE automation to something more efficient. I have seen other posts where they were able to pull the data back using the MSXML object. This is what I was able to build from what I read but am not having any luck figuring out how to pass more than one of the form options. This is a company specific/internal website so unfortunately it is not available externally for me to be able to post the link example.
The element ID's are as follows; dlDivision, dlLocation, calRptDate, lbAreas, btnGenReport.
Public Sub XMLhttp_Search_Extract()
Dim URL As String
Dim XMLreq As Object
Dim POSTdata As String
Dim i As Integer
URL = "somewebURL.test.aspx"
POSTdata = "(" & Q("dlDivision") & ":" & Q("divisionNAMEHERE") & "," & Q("dlLocation") & ":" & Q("123 - Location") & ")"
Set XMLreq = CreateObject("MSXML2.XMLHTTP")
With XMLreq
.Open "POST", URL, False
.setRequestHeader "User-Agent", "Moilla/5.0 (Windows NT 5.1; rv:23.0) Gecko/20100101 Firefox/23.0"
.setRequestHeader "Referer", "somewebURL.test.aspx"
.setRequestHeader "Content-Type", "application/json; charset=utf-8"
.Send (POSTdata)
For i = 1 To Len(.responseText) Step 1023
MsgBox Mid(.responseText, i, i + 1023), _
Title:=i & " to " & Min(i + 1023 - 1, Len(.responseText)) & " of " & Len(.responseText)
Next i
End With
End Sub
Private Function Q(text As String) As String
Q = Chr(34) & text & Chr(34)
End Function
Private Function Min(n1 As Long, n2 As Long) As Long
Min = IIf(n1 < n2, n1, n2)
End Function
I send messages form Excel to telegram. It works nice.
But how can I send a photo? I don't understand it (https://core.telegram.org/bots/api#sendphoto)
Thanks for help!
My send Message:
Dim objRequest As Object
Dim strChatId As String
Dim strMessage As String
Dim strPostData As String
Dim strResponse As String
strChatId = Worksheets("Einstellungen").Cells(3, "AB")
strMessage = Report
APIcode = Worksheets("Einstellungen").Cells(2, "AB")
strPostData = "chat_id=" & strChatId & "&text=" & strMessage
Set objRequest = CreateObject("MSXML2.XMLHTTP")
With objRequest
.Open "POST", "https://api.telegram.org/" & APIcode & "/sendMessage?", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (strPostData)
GetSessionId = .responseText
End With
If your code is working as-is for plain text messages then you should only need to make a couple changes to it.
You're probably currently using the API's sendMessage method, which takes the chat_id and text parameters.
You want to use the sendPhoto method, which tales the chat_id and photo parameters (but no text parameter).
So this is a bit of a shot in the dark since I've never used or heard of Telegram and I don't have a key, so I can't test it, but theoretically, you could send a photo from a URL like this:
Sub telegram_SendPhoto()
Const photoURL = "https://i.imgur.com/0eH6d1v.gif" 'URL of photo
Dim objRequest As Object, strChatId As String, APIcode As String
Dim strPostData As String, strResponse As String
strChatId = Worksheets("Einstellungen").Cells(3, "AB")
APIcode = Worksheets("Einstellungen").Cells(2, "AB")
strPostData = "chat_id=" & strChatId & "&photo=" & photoURL
Set objRequest = CreateObject("MSXML2.XMLHTTP")
With objRequest
.Open "POST", "https://api.telegram.org/" & APIcode & "/sendPhoto?", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (strPostData)
strResponse = .responseText
End With
MsgBox strResponse
End Sub
Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet (above), or upload a new photo using multipart/form-data. More info on Sending Files ยป
I'm going to have multiple instrument numbers and URLs to run this code through. The instrument numbers will start in Column B from Row 8 and down. This VBA currently only runs instrument number 19930074944. How can I have it loop through all these instrument numbers and skip blank cells?
searchResultsURL = baseURL & "GetRecDataDetail.aspx?rec=19930074944&suf=&bdt=1/1/1947&edt=11/18/2016&nm=&doc1=&doc2=&doc3=&doc4=&doc5="
So I need to edit it so that it's:
searchResultsURL = baseURL & "GetRecDataDetail.aspx?rec= & InstNum & "&suf=&bdt=1/1/1947&edt=11/18/2016&nm=&doc1=&doc2=&doc3=&doc4=&doc5="
Then InstNum has to reference B8 and down. And run all this code on each different URL. I have no idea how to do that. Thanks so much!
Option Explicit
Public Sub Download_PDF()
Dim baseURL As String, searchResultsURL As String, pdfURL As String, PDFdownloadURL As String
Dim httpReq As Object
Dim HTMLdoc As Object
Dim PDFlink As Object
Dim cookie As String
Dim downloadFolder As String, localFile As String
Const WinHttpRequestOption_EnableRedirects = 6
'Folder in which the downloaded file will be saved
downloadFolder = ThisWorkbook.Path
If Right(downloadFolder, 1) <> "\" Then downloadFolder = downloadFolder & "\"
baseURL = "http://recorder.maricopa.gov/recdocdata/"
searchResultsURL = baseURL & "GetRecDataDetail.aspx? rec=19930074944&suf=&bdt=1/1/1947&edt=11/18/2016&nm=&doc1=&doc2=&doc3=&doc4=&doc5="
Set httpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
With httpReq
'Send GET to request search results page
.Open "GET", searchResultsURL, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0"
.Send
cookie = .getResponseHeader("Set-Cookie")
'Put response in HTMLDocument for parsing
Set HTMLdoc = CreateObject("HTMLfile")
HTMLdoc.body.innerHTML = .responseText
'Get PDF URL from pages link
'< a id="ctl00_ContentPlaceHolder1_lnkPages" title="Click to view unofficial document"
' href="unofficialpdfdocs.aspx?rec=19930074944&pg=1&cls=RecorderDocuments&suf=" target="_blank">11< /a>
Set PDFlink = HTMLdoc.getElementById("ctl00_ContentPlaceHolder1_lnkPages")
pdfURL = Replace(PDFlink.href, "about:", baseURL)
'Send GET request to the PDF URL with automatic http redirects disabled. This returns a http 302 status (Found) with the Location header containing the URL of the PDF file
.Open "GET", pdfURL, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0"
.setRequestHeader "Referer", searchResultsURL
.setRequestHeader "Set-Cookie", cookie
.Option(WinHttpRequestOption_EnableRedirects) = False
.Send
PDFdownloadURL = .getResponseHeader("Location")
'Send GET to request the PDF file download
.Open "GET", PDFdownloadURL, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/46.0"
.setRequestHeader "Referer", pdfURL
.Send
End With
End Sub
Something like this:
Sub DoAll()
Dim c As Range
Set c = Activesheet.Range("B8")
Do While c.Value<>""
Download_PDF c.Value
Set c = c.offset(1,0) 'next value
Loop
End sub
Edit your original code to include a parameter (relevant parts shown only)
Public Sub Download_PDF(InsNumber)
'....
'....
searchResultsURL = baseURL & "GetRecDataDetail.aspx?rec=" & InsNumber & _
"&suf=&bdt=1/1/1947&edt=11/18/2016&nm=&doc1=&doc2=&doc3=&doc4=&doc5="
'....
'....
End Sub
Hi The below code should work for you..Looping through all the elements..
Note: change sheet1 to required sheet.Pls mark as answer.
Option Explicit
Public Sub Download_PDF()
Dim baseURL As String, searchResultsURL As String, pdfURL As String, PDFdownloadURL As String
Dim httpReq As Object
Dim HTMLdoc As Object
Dim PDFlink As Object
Dim cookie As String
Dim downloadFolder As String, localFile As String
Const WinHttpRequestOption_EnableRedirects = 6
'Folder in which the downloaded file will be saved
downloadFolder = ThisWorkbook.Path
If Right(downloadFolder, 1) <> "\" Then downloadFolder = downloadFolder & "\"
baseURL = "http://recorder.maricopa.gov/recdocdata/"
Set httpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim Instnum As String
Dim i As Integer
For i = 8 To Sheet1.Range("b" & Rows.Count).End(xlUp).Row
Instnum = Sheet1.Cells(i, 2).Value
searchResultsURL = baseURL & "GetRecDataDetail.aspx? rec=" & Instnum & "&suf=&bdt=1/1/1947&edt=11/18/2016&nm=&doc1=&doc2=&doc3=&doc4=&doc5="
With httpReq
'Send GET to request search results page
.Open "GET", searchResultsURL, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0"
.Send
cookie = .getResponseHeader("Set-Cookie")
'Put response in HTMLDocument for parsing
Set HTMLdoc = CreateObject("HTMLfile")
HTMLdoc.body.innerHTML = .responseText
'Get PDF URL from pages link
'< a id="ctl00_ContentPlaceHolder1_lnkPages" title="Click to view unofficial document"
' href="unofficialpdfdocs.aspx?rec=19930074944&pg=1&cls=RecorderDocuments&suf=" target="_blank">11< /a>
Set PDFlink = HTMLdoc.getElementById("ctl00_ContentPlaceHolder1_lnkPages")
pdfURL = Replace(PDFlink.href, "about:", baseURL)
'Send GET request to the PDF URL with automatic http redirects disabled. This returns a http 302 status (Found) with the Location header containing the URL of the PDF file
.Open "GET", pdfURL, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0"
.setRequestHeader "Referer", searchResultsURL
.setRequestHeader "Set-Cookie", cookie
.Option(WinHttpRequestOption_EnableRedirects) = False
.Send
PDFdownloadURL = .getResponseHeader("Location")
'Send GET to request the PDF file download
.Open "GET", PDFdownloadURL, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/46.0"
.setRequestHeader "Referer", pdfURL
.Send
End With
Next i
End Sub
Here is the source of a function I use get HTML code for further proccessing:
Public Function DownloadTextFile(url As String) As String
Dim oHTTP As WinHttp.WinHttpRequest
Set oHTTP = New WinHttp.WinHttpRequest
oHTTP.Open Method:="GET", url:=url, async:=False
oHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
'oHTTP.setRequestHeader "Content-Type", "multipart/form-data; "
oHTTP.setRequestHeader "Content-Type", "text/html; charset=utf-8"
oHTTP.Option(WinHttpRequestOption_EnableRedirects) = True
oHTTP.send
Dim success As Boolean
success = oHTTP.waitForResponse()
If Not success Then
Debug.Print "DOWNLOAD FAILED!"
Exit Function
End If
Dim responseText As String
Debug.Print oHTTP.responseText
responseText = oHTTP.responseText
'Set fs = CreateObject("Scripting.FileSystemObject")
'Set a = fs.CreateTextFile("c:\testfile.txt", True, False)
'Set a = fs.CreateTextFile("c:\testfile.txt", True, True)
'a.WriteLine oHTTP.responseText
'a.Close
Set oHTTP = Nothing
DownloadTextFile = responseText
End Function
It works for most pages, but for some pages the responseText is No Mapping for the Unicode character exists in the target multi-byte code page.
Here is an example of web page for which the responseText is No Mapping for the Unicode character exists in the target multi-byte code page
http://bzp0.portal.uzp.gov.pl/index.php?ogloszenie=browser&action=search&rodzajzamowienia=B&rodzajogloszenia=1&aktualne=1&datapublikacji_rodzaj=5&iloscwynikownastronie=20&offset=20
and here is a suspicious character that can't be encoded (screenshot from google chrome):
http://imageshack.us/photo/my-images/585/errsource.png/
From time to time on same website but for different search result this function does not generate error, but then, the HTML source in immidiate window is like ?????? ...
Any ideas how to make it work?
Solution that worked for me:
responseText = VBA.Strings.StrConv(oHTTP.ResponseBody, vbUnicode)
Note the use of ResponseBody instead of ResponseText
Try to use StrConv:
DownloadTextFile = VBA.Strings.StrConv(responseText, vbUnicode)
vbUnicode: Converts the string to Unicode using the default code page of the system. (Not available on the Macintosh.)