22.实例:利用JS点击百度翻译
Dim temp, hWeb, sRet, 待翻译的文字
//变量赋值
待翻译的文字 = "早上好"
//绑定浏览器
hWeb = WebBrowser.BindBrowser("chrome", 10000, {"bContinueOnError": false, "iDelayAfter": 300, "iDelayBefore": 200})
//利用JS向待翻译的输入框里输入文字,F12检查输入框属性,在输入框代码右键→Copy→Copy JS path,若想加入变量:先变为变量模式,将原来的文字用"&&"替换,中间加入变量
sRet = WebBrowser.RunJS(hWeb, "function(){document.querySelector("#baidu_translate_input").value="" & 待翻译的文字 & "";return 123}", true, {"bContinueOnError": false, "iDelayAfter": 300, "iDelayBefore": 200})
//利用JS向点击“翻译”
sRet = WebBrowser.RunJS(hWeb, "function(){document.querySelector("#translate-button").click();return 123}", true, {"bContinueOnError": false, "iDelayAfter": 300, "iDelayBefore": 200})
//利用JS向点击获取翻译结果,a为翻译结果,注意返回值a,“.innerText”得到文本
sRet = WebBrowser.RunJS(hWeb, "function(){a=document.querySelector("#main-outer > div > div > div.translate-wrap > div.translateio > div.translate-main.clearfix > div.trans-right > div > div > div.output-bd > p.ordinary-output.target-output.clearfix > span").innerText\n;return a}", true, {"bContinueOnError": false, "iDelayAfter": 300, "iDelayBefore": 200})
//输出翻译结果
TracePrint($PrevResult)
还可以利用Css selector的方法获得翻译结果:在对象上右键→Copy→Copy Css selector,复制到Ub中后加“.textContent”。d为翻译结果
sRet = WebBrowser.RunJS(hWeb,"function(){d=document.querySelector("#main-outer > div > div > div.translate-wrap > div.translateio > div.translate-main.clearfix > div.trans-right > div > div > div.output-bd > p.ordinary-output.target-output.clearfix > span").textContent;return d}",true,{"bContinueOnError":false,"iDelayAfter":300,"iDelayBefore":200})