You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
const{ Builder, By }=require("selenium-webdriver");letfs=require("fs");(asyncfunctionexample(){letdriver=awaitnewBuilder().forBrowser("chrome").build();awaitdriver.get("https://www.example.com");letele=awaitdriver.findElement(By.css("h1"));// Captures the element screenshotletencodedString=awaitele.takeScreenshot(true);awaitfs.writeFileSync("./image.png",encodedString,"base64");awaitdriver.quit();})();
大多数由于使用 Selenium 和 WebDriver 而产生的间歇性问题都与浏览器和用户指令之间的 竞争条件 有关。例如,用户指示浏览器导航到一个页面,然后在试图查找元素时得到一个 no such element 的错误。
constwebdriver=require("selenium-webdriver"),By=webdriver.By;constfile_path="file:///"+__dirname+"/demo3.html";(asyncfunctionmyFunction(){constdriver=awaitnewwebdriver.Builder().forBrowser("chrome").build();awaitdriver.get(file_path);constelement=driver.findElement(By.css("p"));assert.strictEqual(awaitelement.getText(),"Hello from JavaScript!");})();
constdriver=awaitnewwebdriver.Builder().forBrowser("chrome").build();constdocumentInitialised=()=>driver.executeScript("return initialised");awaitdriver.get(file_path);awaitdriver.wait(()=>documentInitialised(),10000);constelement=driver.findElement(By.css("p"));assert.strictEqual(awaitelement.getText(),"Hello from JavaScript!");
将 条件 作为函数引用传递,等待 将会重复运行直到其返回值为 true。
letele=awaitdriver.wait(until.elementLocated(By.css("p")),10000);letfoo=awaitele.getText();assert(foo=="Hello from JavaScript");
隐式等待是告诉 WebDriver 如果在查找一个或多个不是立即可用的元素时轮询 DOM 一段时间。默认设置为 0,表示禁用。一旦设置好,隐式等待就被设置为会话的生命周期。
(asyncfunction(){// Apply timeout for 10 secondsawaitdriver.manage().setTimeouts({implicit: 10000});// Navigate to urlawaitdriver.get("http://somedomain/url_that_delays_loading");letwebElement=driver.findElement(By.id("myDynamicElement"));})();
const{ Builder, until }=require("selenium-webdriver");(asyncfunctionexample(){letdriver=awaitnewBuilder().forBrowser("firefox").build();awaitdriver.get("http://somedomain/url_that_delays_loading");// Waiting 30 seconds for an element to be present on the page, checking// for its presence once every 5 seconds.letfoo=awaitdriver.wait(until.elementLocated(By.id("foo")),30000,"Timed out after 30 seconds",})();
6. JavaScript 警告框,提示框和确认框
demo 路径 demo/demo4.js
6.1. Alerts 警告框
WebDriver 可以从弹窗获取文本并接受或关闭这些警告.
constwebdriver=require("selenium-webdriver"),By=webdriver.By,until=webdriver.until;constfile_path="file:///"+__dirname+"/demo4.html";(asyncfunctionmyFunction(){constdriver=awaitnewwebdriver.Builder().forBrowser("chrome").build();awaitdriver.get(file_path);awaitdriver.findElement(By.css("button")).click();// Wait for the alert to be displayedawaitdriver.wait(until.alertIsPresent());// Store the alert in a variableletalert=awaitdriver.switchTo().alert();//Press the OK buttonawaitalert.accept();})();
6.2. Confirm 确认框
确认框类似于警告框, 不同之处在于用户还可以选择取消消息
constwebdriver=require("selenium-webdriver"),By=webdriver.By,until=webdriver.until;constfile_path="file:///"+__dirname+"/demo4.html";(asyncfunctionmyFunction(){constdriver=awaitnewwebdriver.Builder().forBrowser("chrome").build();awaitdriver.get(file_path);awaitdriver.findElement(By.css("button")).click();// Wait for the alert to be displayedawaitdriver.wait(until.alertIsPresent());// Store the alert in a variableletalert=awaitdriver.switchTo().alert();//Press the Cancel buttonawaitalert.dismiss();})();
awaitdriver.findElement(By.css("button")).click();// Wait for the alert to be displayedawaitdriver.wait(until.alertIsPresent());// Store the alert in a variableletalert=awaitdriver.switchTo().alert();//Type your messageawaitalert.sendKeys("Selenium");//Press the OK buttonawaitalert.accept();
constwebdriver=require("selenium-webdriver"),By=webdriver.By;Key=webdriver.Key;constdriver=awaitnewwebdriver.Builder().forBrowser("chrome").build();awaitdriver.get("https://www.baidu.com");// await driver.findElement(By.id("kw")).sendKeys("selenium");// await driver.findElement(By.id("su")).click();// 同样功能// Enter text and perform keyboard action "Enter"awaitdriver.findElement(By.id("kw")).sendKeys('selenium',Key.ENTER);
9.2. keyDown
keyDown用于模拟按下辅助按键(CONTROL, SHIFT, ALT)的动作.
// Perform action ctrl + A (modifier CONTROL + Alphabet A) to select the pageawaitdriver.actions().keyDown(Key.CONTROL).sendKeys('a').perform();// mac commandawaitdriver.actions().keyDown(Key.COMMAND).sendKeys('a').perform();
9.3. keyUp
keyUp用于模拟辅助按键(CONTROL, SHIFT, ALT)弹起或释放的操作.
// Enters text "selenium" with keyDown SHIFT key and after keyUp SHIFT key constsearch=driver.findElement(By.id('kw'));awaitdriver.actions().click(search).keyDown(Key.SHIFT).sendKeys("selenium")// .keyUp(Key.SHIFT)// .sendKeys("selenium").perform();
// Store 'SearchInput' elementconstsearchInput=driver.findElement(By.id('kw'));awaitsearchInput.sendKeys("selenium");// Clears the entered textawaitsearchInput.clear();
10. 鼠标动作
demo路径demo/demo7.js
10.1. clickAndHold
它将移动到该元素,然后在给定元素的中间单击(不释放).
letsearchBtn=driver.findElement(By.id("su"));constactions=driver.actions({async: true});// Perform mouseMove to element and mouseDown (press) action on the elementawaitactions.move({origin: searchBtn}).press().perform();
10.2. contextClick
首先将鼠标移动到元素的位置, 然后在给定元素执行上下文点击(右键单击).
// Perform context-click action on the elementawaitactions.contextClick(searchBtn).perform();
10.3. doubleClick
移动到该元素, 并在给定元素的中间双击.
// Perform double-click action on the elementawaitactions.doubleClick(searchBtn).perform();
10.4. moveToElement
将鼠标移到元素的中间. 执行此操作时, 该元素也会滚动到视图中.
constbaiduLink=driver.findElement(By.linkText("帮助"));// Performs mouse move action onto the elementawaitactions.move({origin: baiduLink}).perform();
letoffset=awaitsearchBtn.getRect();letx=awaitoffset.x;lety=awaitoffset.y;// Performs mouse move action onto the elementawaitactions.move({x: parseInt(x),y: parseInt(y)}).pause(3000).perform();
10.6. dragAndDrop
在源元素上单击并按住,然后移动到目标元素的位置后释放鼠标.
awaitdriver.get("https://crossbrowsertesting.github.io/drag-and-drop");// Store 'box A' as source elementletsourceEle=driver.findElement(By.id("draggable"));// Store 'box B' as source elementlettargetEle=driver.findElement(By.id("droppable"));constactions=driver.actions({async: true});// Performs drag and drop action of sourceEle onto the targetEleawaitactions.dragAndDrop(sourceEle,targetEle).perform();
// set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'awaitdriver.manage().addCookie({name:'key',value: 'value',sameSite:'Strict'});awaitdriver.manage().addCookie({name:'key',value: 'value',sameSite:'Lax'});console.log(awaitdriver.manage().getCookie('key'));