![](/img/trans.png)
[英]Capture console error using JavascriptExecutor class in selenium
[英]Selenium Datepicker using JavascriptExecutor
請告知是否接受這種方法來使用 Selenium 取貨
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.spicejet.com/");
Thread.sleep(3000);
JavascriptExecutor js = ((JavascriptExecutor)driver);
js.executeScript ("document.getElementById('ctl00_mainContent_view_date1').removeAttribute('readonly',0);");
WebElement onwards_date = driver.findElement(By.id("ctl00_mainContent_view_date1"));
onwards_date.clear();
onwards_date.sendKeys("28/02");
js.executeScript ("document.getElementById('ctl00_mainContent_view_date2').removeAttribute('readonly',0);");
WebElement return_Date = driver.findElement(By.id("ctl00_mainContent_view_date2"));
return_Date.clear();
return_Date.sendKeys("27/03");
您可以使用 JavaScript 設置值以輸入ctl00_mainContent_txt_Fromdate
id for from date和ctl00_mainContent_txt_Todate
id for to date 。 您不會看到 UI 中的值發生變化,但它確實有效。
js.executeScript("arguments[0].value = arguments[1]",
driver.findElement(By.id("ctl00_mainContent_txt_Fromdate")), "28-02-2020");
不要在代碼中使用sleep
,而是使用WebDriverWait
,它使 WebDriver 等待特定條件,並且僅在需要時等待。
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
JavascriptExecutor js = (JavascriptExecutor) driver;
driver.manage().window().maximize();
driver.get("https://www.spicejet.com/");
// Wait for Search button to be clickable, the state in which we assume that the site has loaded
WebElement searchButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("ctl00_mainContent_btn_FindFlights")));
// Select From and To Cities
js.executeScript("arguments[0].value = arguments[1]",
driver.findElement(By.id("ctl00_mainContent_txt_Fromdate")), "28-02-2020");
js.executeScript("arguments[0].value = arguments[1]",
driver.findElement(By.id("ctl00_mainContent_txt_Todate")), "01-03-2020");
searchButton.click();
要使用來自JavascriptExecutor 的Selenium的executeScript()方法在網站https://www.spicejet.com/的DEPART DATE字段中獲取日期,您可以使用以下定位器策略:
代碼塊:
System.setProperty("webdriver.chrome.driver", "C:\\\\Utility\\\\BrowserDrivers\\\\chromedriver.exe"); ChromeOptions options = new ChromeOptions(); options.addArguments("start-maximized"); options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation")); options.setExperimentalOption("useAutomationExtension", false); WebDriver driver = new ChromeDriver(options); driver.get("https://www.spicejet.com/"); WebElement element = driver.findElement(By.cssSelector("input[name$= 'txt_Fromdate']")); ((JavascriptExecutor)driver).executeScript("arguments[0].removeAttribute('readonly')", element); WebElement newElement = driver.findElement(By.cssSelector("input[name$= 'txt_Fromdate']")); ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('value','28/02')", newElement);
瀏覽器快照:
您可以在以下位置找到一些相關的詳細討論:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.