public void emaildetails() throws SAXException, IOException, Exception { driver.findElement(By.id("To")).sendKeys("*****@*****.**"); driver.findElement(By.id("Subject")).sendKeys("test mail"); parenthandle(); /*WebElement frame1= driver.findElement(By.xpath(".//*[@id='cke_1_contents']/iframe")); driver.switchTo().frame(frame1); WebElement div=driver.findElement(By.xpath("//div"));*/ /*DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); db.parse("https://mail.qainfotech.net/Worldclient.dll?Session=XPED40H3940YT&View=Compose&New=Yes"); */ // org.jsoup.nodes.Document doc=Jsoup.connect("https://mail.qainfotech.net/Worldclient.dll?Session=XPED40H3940YT&View=Compose&New=Yes").get(); // doc.g /*doc.getDocumentElement().normalize(); XPath xPath = XPathFactory.newInstance().newXPath(); Node node = (Node)xPath.evaluate(".//*[@id='cke_1_contents']/iframe//div", doc.getDocumentElement(), XPathConstants.NODESET);*/ JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("document.getElementsByClassName('cke_wysiwyg_frame cke_reset')[0].contentDocument.getElementsByTagName('div')[0].innerHTML='<p> this is a test mail </p>'", ""); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); sendmail(); }
public static void setAttribute(WebElement element, String attributeName, String value) { WrapsDriver wrappedElement = (WrapsDriver) element; JavascriptExecutor driver = (JavascriptExecutor) wrappedElement.getWrappedDriver(); driver.executeScript( "arguments[0].setAttribute(arguments[1], arguments[2])", element, attributeName, value); }
public Object[] getWgVariableKeysFromPage(String url, String variableName) { getUrl(url); JavascriptExecutor js = (JavascriptExecutor) driver; Map<String, Integer> variableValueFromPage = (Map<String, Integer>) js.executeScript("return eval(arguments[0])", variableName); return variableValueFromPage.keySet().toArray(); }
@Test(groups = {"taobao"}) public void webDriver() { driver.get("http://m.taobao.com/"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); MobileElement tmall = (MobileElement) driver.findElementByXPath("//div[@id='a6636-1']"); tmall.swipe(SwipeElementDirection.DOWN, 1000); tmall.tap(1, 1000); HashMap<String, Integer> tapObject = new HashMap<String, Integer>(); tapObject.put("x", 120); tapObject.put("y", 120); tapObject.put("touchCount", 1); tapObject.put("duration", 1200); driver.executeScript("mobile: tap", tapObject); JavascriptExecutor js = (JavascriptExecutor) driver; HashMap<String, Double> flickObject = new HashMap<String, Double>(); flickObject.put("startX", 200.0); flickObject.put("startY", 700.5); flickObject.put("endX", 200.2); flickObject.put("endY", 100.5); js.executeScript("mobile: flick", flickObject); TouchAction action = new TouchAction(driver); action.press(tmall).waitAction(400).perform(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); List<WebElement> elements = driver.findElementsByXPath("//ul/li/a[@class='card-item card-style-chn']"); for (WebElement e : elements) { System.out.println(e.getAttribute("href")); } driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); System.out.println(driver.getPageSource()); }
public void stop() { String primaryTestSuiteName = _liferaySelenium.getPrimaryTestSuiteName(); if (primaryTestSuiteName != null) { JavascriptExecutor javascriptExecutor = (JavascriptExecutor) _webDriver; String content = (String) javascriptExecutor.executeScript( "return window.document.getElementsByTagName('html')[0]." + "outerHTML;"); String fileName = _liferaySelenium.getProjectDir() + "portal-web\\test-results\\functional\\TEST-" + primaryTestSuiteName + ".html"; File file = new File(fileName); try { FileUtil.write(file, content); } catch (Exception e) { } } _webDriver.quit(); }
private static void changeContentEditableValueInHtmlUnit( WebDriver driver, WebElement element, String value) { // we resort to JavaScript when it is enabled if (((HtmlUnitDriver) driver).isJavascriptEnabled()) { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript( "arguments[0]['innerText' in arguments[0] ? 'innerText' : 'textContent'] = arguments[1];", element, value); } else { // or use reflection if JS is not enabled // (this method is not preferred as it relies on HtmlUnit's internals, which can change // without notice) try { // #HtmlUnit #reflection #hack Method getElementMethod = org.openqa.selenium.htmlunit.HtmlUnitWebElement.class.getDeclaredMethod("getElement"); getElementMethod.setAccessible(true); HtmlElement he = (HtmlElement) getElementMethod.invoke(element); HTMLElement e = (HTMLElement) he.getScriptObject(); e.setInnerText(value); } catch (Exception e) { LOGGER.warn("Unable to set HtmlUnitWebElement's innerText.", e); } } }
@Test public void testUntitled() throws Exception { login.testUntitled(); JavascriptExecutor js = (JavascriptExecutor) driver; driver.findElement(By.cssSelector("a[id=itemMM50]")).click(); driver.findElement(By.cssSelector("div[id=mmSUB117]")).click(); js.executeScript( "chamaItemMenu('/citsmart/pages/dinamicViews/dinamicViews.load?identificacao=ReqSLA')"); Thread.sleep(2000L); driver.findElement(By.cssSelector("span.combo-arrow.combo-arrow-hover")).click(); driver.findElement(By.cssSelector("input.combo-text.validatebox-text")).clear(); driver.findElement(By.cssSelector("input.combo-text.validatebox-text")).sendKeys("layanne"); driver.findElement(By.cssSelector("div.datagrid-cell.datagrid-cell-c3-NOME")).click(); driver.findElement(By.id("REQUISITADOEM")).click(); driver.findElement(By.cssSelector("span.ui-icon.ui-icon-circle-triangle-e")).click(); driver.findElement(By.cssSelector("span.ui-icon.ui-icon-circle-triangle-e")).click(); driver.findElement(By.cssSelector("span.ui-icon.ui-icon-circle-triangle-e")).click(); driver.findElement(By.linkText("18")).click(); driver.findElement(By.id("ASSUNTO")).clear(); driver.findElement(By.id("ASSUNTO")).sendKeys("teste"); driver.findElement(By.id("DETALHAMENTO")).clear(); driver.findElement(By.id("DETALHAMENTO")).sendKeys("teste"); driver.findElement(By.id("btnGravar")).click(); driver.switchTo().alert().getText().endsWith("Registro inserido com sucesso"); Thread.sleep(2000L); driver.switchTo().alert().accept(); }
// XPath Generator JavaScript private String GenerateElementXPath(WebDriver driver, WebElement element) { JavascriptExecutor js = (JavascriptExecutor) driver; return (String) js.executeScript( "gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]).toLowerCase();", element); }
public void selectTab(String tabName) { try { int idx = 0; boolean found = false; List<WebElement> tabs = _jQueryUITab.findElements(By.cssSelector(".ui-tabs-nav > li")); for (WebElement tab : tabs) { if (tabName.equals(tab.getText().toString())) { WrapsDriver wrappedElement = (WrapsDriver) _jQueryUITab; JavascriptExecutor driver = (JavascriptExecutor) wrappedElement.getWrappedDriver(); driver.executeScript( "jQuery(arguments[0]).tabs().tabs('select',arguments[1]);", _jQueryUITab, idx); found = true; break; } idx++; } if (found == false) { throw new Exception("Could not find tab '" + tabName + "'"); } } catch (Exception e) { // TODO: handle exception } }
private void sendContextMessage(String step) { try { JavascriptExecutor je = (JavascriptExecutor) webDriverProvider.get(); je.executeScript("sauce:context=Step: " + step); } catch (Exception e) { } }
@Test public void dropdownTest() throws InterruptedException { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("alert('hello world')"); Thread.sleep(5000); AlertHandler(); }
public void hoverClickAndViewStudentPhotoOnHeading(int panelHeadingIndex, String urlRegex) throws Exception { JavascriptExecutor jsExecutor = (JavascriptExecutor) browser.driver; String idOfPanelHeading = "panelHeading-" + panelHeadingIndex; WebElement photoDiv = browser .driver .findElement(By.id(idOfPanelHeading)) .findElement(By.className("profile-pic-icon-hover")); jsExecutor.executeScript("arguments[0].scrollIntoView(true);", photoDiv); Actions actions = new Actions(browser.driver); actions.moveToElement(photoDiv).perform(); waitForElementPresence(By.cssSelector(".popover-content")); jsExecutor.executeScript( "document.getElementsByClassName('popover-content')[0]" + ".getElementsByTagName('a')[0].click();"); waitForElementPresence(By.cssSelector(".popover-content > img")); AssertHelper.assertContainsRegex( urlRegex, browser .driver .findElements(By.cssSelector(".popover-content > img")) .get(0) .getAttribute("src")); jsExecutor.executeScript( "document.getElementsByClassName('popover')[0].parentNode.removeChild(document.getElementsByClassName('popover')[0])"); }
public void clickViewPhotoLink(int panelBodyIndex, String urlRegex) throws Exception { String idOfPanelBody = "panelBodyCollapse-" + panelBodyIndex; WebElement photoCell = browser .driver .findElement(By.id(idOfPanelBody)) .findElements(By.cssSelector(".profile-pic-icon-click")) .get(0); JavascriptExecutor jsExecutor = (JavascriptExecutor) browser.driver; jsExecutor.executeScript( "document.getElementById('" + idOfPanelBody + "')" + ".getElementsByClassName('profile-pic-icon-click')[0]" + ".getElementsByTagName('a')[0].click();"); Actions actions = new Actions(browser.driver); actions.moveToElement(photoCell).perform(); waitForElementPresence(By.cssSelector(".popover-content > img")); List<WebElement> photos = browser.driver.findElements(By.cssSelector(".popover-content > img")); AssertHelper.assertContainsRegex(urlRegex, photos.get(photos.size() - 1).getAttribute("src")); actions.moveByOffset(100, 100).click().perform(); }
public void hoverAndViewStudentPhotoOnBody(int panelBodyIndex, String urlRegex) throws Exception { String idOfPanelBody = "panelBodyCollapse-" + panelBodyIndex; WebElement photoLink = browser .driver .findElements(By.cssSelector('#' + idOfPanelBody + "> .panel-body > .row")) .get(0) .findElements(By.className("profile-pic-icon-hover")) .get(0); Actions actions = new Actions(browser.driver); actions.moveToElement(photoLink).perform(); waitForElementPresence(By.cssSelector(".popover-content > img")); ThreadHelper.waitFor(500); AssertHelper.assertContainsRegex( urlRegex, browser .driver .findElements(By.cssSelector(".popover-content > img")) .get(0) .getAttribute("src")); JavascriptExecutor jsExecutor = (JavascriptExecutor) browser.driver; jsExecutor.executeScript( "document.getElementsByClassName('popover')[0].parentNode.removeChild(document.getElementsByClassName('popover')[0])"); }
public static void typeAlloyEditor(WebDriver webDriver, String locator, String value) { WebElement webElement = getWebElement(webDriver, locator); WrapsDriver wrapsDriver = (WrapsDriver) webElement; WebDriver wrappedWebDriver = wrapsDriver.getWrappedDriver(); JavascriptExecutor javascriptExecutor = (JavascriptExecutor) wrappedWebDriver; StringBuilder sb = new StringBuilder(); sb.append("CKEDITOR.instances[\""); String titleAttribute = getAttribute(webDriver, locator + "@title"); int x = titleAttribute.indexOf(","); int y = titleAttribute.indexOf(",", x + 1); if (y == -1) { y = titleAttribute.length(); } sb.append(titleAttribute.substring(x + 2, y)); sb.append("\"].setData(\""); sb.append(HtmlUtil.escapeJS(value.replace("\\", "\\\\"))); sb.append("\");"); javascriptExecutor.executeScript(sb.toString()); }
public static void executeJavaScriptEvent( WebDriver webDriver, String locator, String eventType, String event) { WebElement webElement = getWebElement(webDriver, locator); WrapsDriver wrapsDriver = (WrapsDriver) webElement; WebDriver wrappedWebDriver = wrapsDriver.getWrappedDriver(); JavascriptExecutor javascriptExecutor = (JavascriptExecutor) wrappedWebDriver; if (!webElement.isDisplayed()) { scrollWebElementIntoView(webDriver, webElement); } StringBuilder sb = new StringBuilder(6); sb.append("var element = arguments[0];"); sb.append("var event = document.createEvent('"); sb.append(eventType); sb.append("');event.initEvent('"); sb.append(event); sb.append("', true, false);"); sb.append("element.dispatchEvent(event);"); javascriptExecutor.executeScript(sb.toString(), webElement); }
public void uploadProfile(String provider, String name, String context, String version) throws InterruptedException, IOException { driver.findElement(By.id(uiElementMapper.getElement("my.profile.region.tab.id"))).click(); driver .findElement(By.linkText(uiElementMapper.getElement("my.profile.new.profile.add.link"))) .click(); WebElement profileName = driver.findElement(By.id(uiElementMapper.getElement("my.profile.name.id"))); profileName.sendKeys(provider); WebElement profileFirstName = driver.findElement(By.id(uiElementMapper.getElement("my.profile.first.name.id"))); profileFirstName.sendKeys(name); WebElement profileLastName = driver.findElement(By.id(uiElementMapper.getElement("my.profile.last.name.id"))); profileLastName.sendKeys(context); WebElement profileEmail = driver.findElement(By.id(uiElementMapper.getElement("my.profile.email.id"))); profileEmail.sendKeys(version); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("validate()"); log.info("successfully Saved"); }
@Override public void scrollToElement(By by) { JavascriptExecutor javascriptExecutor = (JavascriptExecutor) augmentedWebDriverProvider.get(); AugmentedWebElement elementPresent = findElementPresent(by); javascriptExecutor.executeScript( "arguments[0].scrollIntoView(true);", elementPresent.webElement()); }
/** * 实现功能:爬取主题页面,输入是 “页面保存路径filepath” 和 “主题页面链接url” 下拉四次主题页面,10秒内没打开页面会重开(问题数目为49-59) 调整 下拉次数 * 可以得到问题数目会 增加 使用技术:Selenium * * @param filePath, url * @throws InterruptedException */ public static void seleniumCrawlerSubject(String filePath, String url) throws InterruptedException { // 设置 // System.setProperty("webdriver.ie.driver","C:\\Program Files\\Internet // Explorer\\IEDriverServer.exe"); // System.out.println("InternetExplorerDriver opened"); File file = new File(filePath); int delay = 12; if (!file.exists()) { // try{ // // } catch(Exception e) { // // } WebDriver driver = new InternetExplorerDriver(); // 5秒内没打开,重新加载 driver.manage().timeouts().pageLoadTimeout(delay, TimeUnit.SECONDS); while (true) { try { driver.get(url); } catch (Exception e) { driver.quit(); driver = new InternetExplorerDriver(); driver.manage().timeouts().pageLoadTimeout(delay, TimeUnit.SECONDS); continue; } break; } System.out.println("Page title is: " + driver.getTitle()); // roll the page JavascriptExecutor JS = (JavascriptExecutor) driver; try { JS.executeScript("scrollTo(0, 5000)"); System.out.println("1"); Thread.sleep(5000); // 调整休眠时间可以获取更多的内容 JS.executeScript("scrollTo(5000, 10000)"); System.out.println("2"); Thread.sleep(5000); JS.executeScript("scrollTo(10000, 30000)"); // document.body.scrollHeight System.out.println("3"); Thread.sleep(5000); JS.executeScript("scrollTo(10000, 80000)"); // document.body.scrollHeight System.out.println("4"); Thread.sleep(5000); } catch (Exception e) { System.out.println("Error at loading the page ..."); driver.quit(); } // save page String html = driver.getPageSource(); saveHtml(filePath, html); System.out.println("save finish"); // Close the browser Thread.sleep(2000); driver.quit(); } else { System.out.println(filePath + "已经存在,不必再次爬取..."); } }
/** * @throws TimeoutException * @throws NoSuchElementException */ public void logout() throws NoSuchElementException, TimeoutException { WebElement logoutButton = fluentWait(By.xpath("//*[@id='loginbox']/ul/li[7]/a")); if (logoutButton != null) { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", logoutButton); } }
@Test(enabled = true, priority = 4) public void ThreemmSolventWeldWasteMuPVCProductPage() throws IOException, InterruptedException { File file = new File("C:\\Selenium\\jenkindemo\\src\\objectRepositry\\Products_PageObjects"); FileInputStream input = new FileInputStream(file); Properties prop = new Properties(); prop.load(input); dr.navigate().to(prop.getProperty("PlumbingWasteProductPage")); dr.findElement(By.xpath(prop.getProperty("SolventWeldWasteMuPVCProducts"))).click(); WebElement Subproductname = dr.findElement(By.xpath(prop.getProperty("subproductname"))); String Subproname = Subproductname.getText(); System.out.println( "***********************************************************************************************"); System.out.println("\t\tThe Sub Product Name is:" + Subproname); dr.findElement(By.xpath(prop.getProperty("32mmSolventWeldWasteMuPVCProducts"))).click(); WebElement Subcatproductname = dr.findElement(By.xpath(prop.getProperty("subproductname"))); String Subcatproname = Subcatproductname.getText(); System.out.println( "***********************************************************************************************"); System.out.println("\t\tThe Sub category Product Name is:" + Subcatproname); WebElement SubProduct = dr.findElement(By.xpath(prop.getProperty("subproduct"))); List<WebElement> list = SubProduct.findElements(By.tagName("div")); int t = list.size(); for (int i = 1; i <= t; i++) { String str1 = prop.getProperty("subproduct_part1"); String str2 = prop.getProperty("subproduct_part2"); dr.findElement(By.xpath(str1 + i + str2)).click(); WebElement productname = dr.findElement(By.xpath(prop.getProperty("subcatproductname"))); String finalcatproname = productname.getText(); System.out.println( "***********************************************************************************************"); System.out.println("\t\tThe Final Product Name is:" + finalcatproname); System.out.println( "***********************************************************************************************"); WebElement FinalSubProduct = dr.findElement(By.xpath(prop.getProperty("FinalProduct"))); List<WebElement> FinalSubproducts = FinalSubProduct.findElements(By.tagName("figure")); int Subtotal = FinalSubproducts.size(); for (int n = 1; n <= Subtotal; n++) { String str5 = prop.getProperty("ProductImage_Part1"); String str6 = prop.getProperty("ProductImage_Part2"); String str8 = prop.getProperty("Finalproductname_part1a"); String str13 = prop.getProperty("popupClose"); int r = Subtotal + 1; JavascriptExecutor jse = (JavascriptExecutor) dr; jse.executeScript("scroll(0,-500);"); TimeUnit.SECONDS.sleep(2); WebElement ProductName = dr.findElement(By.xpath(str5 + n + str8)); String Name = ProductName.getText(); String Proname = Name.replaceAll("[\r\n]+", " "); System.out.println("The Recently viewed product name is:" + Proname); dr.findElement(By.xpath(str5 + n + str6)).click(); dr.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS); // ScreenCapture(); TimeUnit.SECONDS.sleep(2); dr.findElement(By.xpath(str5 + r + str13)).click(); } dr.navigate().to(prop.getProperty("32mmSolventWeldWasteMuPVCProductPage")); } }
/** * Returns the size of clipboard * * @return the size of the clipboard */ public int getClipboardSize() { JavascriptExecutor executer = (JavascriptExecutor) guiAgent.getWebDriver(); Long count = (Long) executer.executeScript( "return window.JSClipboard.getInstance().getLatestClip().isMultiClip == null ? " + "1 : window.JSClipboard.getInstance().getLatestClip().getClipCount();"); return count.intValue(); }
private void scrollToSlotOnMobile(String slotName) { JavascriptExecutor js = driver; js.executeScript( "var element = document.getElementById(arguments[0]);" + "var elementY = element.offsetTop;" + "var elementH = element.offsetHeight;" + "window.scrollTo(0, elementY - elementH);", slotName); }
public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.navigate().to("http://www.google.com"); JavascriptExecutor js = (JavascriptExecutor) driver; System.out.println(js.executeScript("return document.title")); }
@Override public Object executeScript(String script, Object... objects) { JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver; try { return javascriptExecutor.executeScript(script, objects); } catch (WebDriverException e) { LOGGER.error("WebDriverException in executeScript: " + script, e); return null; } }
/** * Checks that all ajax calls are completed on page. * * @param num Number of ajax calls to wait for completion. * @return "true" if completed else "false". */ public String ajaxFinised(String num) { Object isAjaxFinished; JavascriptExecutor js = (JavascriptExecutor) driver; isAjaxFinished = js.executeScript("return jQuery.active == " + num); return isAjaxFinished.toString(); }
protected static void scrollWebElementIntoView(WebDriver webDriver, WebElement webElement) { WrapsDriver wrapsDriver = (WrapsDriver) webElement; WebDriver wrappedWebDriver = wrapsDriver.getWrappedDriver(); JavascriptExecutor javascriptExecutor = (JavascriptExecutor) wrappedWebDriver; javascriptExecutor.executeScript("arguments[0].scrollIntoView();", webElement); }
public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.navigate().to("http://www.google.com"); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("scroll(250, 0)"); // Scroll up js.executeScript("window.scrollBy(0,250)", ""); // Scroll down }
private void showHighlight(By by, WebDriver driver) { try { WebElement foundElement = driver.findElement(by); JavascriptExecutor jsExec = (JavascriptExecutor) driver; jsExec.executeScript("arguments[0].style.border='2px solid blue'", foundElement); this.previousBy = by; } catch (ElementNotVisibleException e) { LOGGER.warn("Highlighting WebElement failed because it is not visible", e); } }
public void scrollPageUp() { JavascriptExecutor js = (JavascriptExecutor) androidDriver; HashMap<String, Double> swipeObject = new HashMap<String, Double>(); swipeObject.put("startX", 0.50); swipeObject.put("startY", 0.95); swipeObject.put("endX", 0.50); swipeObject.put("endY", 0.01); swipeObject.put("duration", 3.0); js.executeScript("mobile: swipe", swipeObject); }