[英]Scrolling to a WebElement and clicking on it
我是自動化的新手,並且正在flipkart網站上練習。 在頁面上:
...當我嘗試通過滾動查看不在頁面視圖中的元素時,出現異常: Element is not clickable
下面是代碼:
WebElement mobile = driver.findElement(By.xpath ("//a[@title='Apple iPhone 6S (Silver, 128 GB) ']"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].scrollIntoView();", mobile);
mobile.click();
我相信由於flipkart中可用的標題而發生了此問題:即使窗口正在滾動到該特定元素,標題也覆蓋了該元素,因此無法單擊它。
誰能解決這個問題?
你可以這樣嘗試
如果您想單擊不在頁面范圍內的元素(無滾動),請嘗試以下方法
public static void main(String[] args) throws InterruptedException { WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get( "http://www.flipkart.com/mobiles/pr?sid=tyy,4io&otracker=clp_mobiles_CategoryLinksModule_0-2_catergorylinks_11_ViewAll"); driver.manage().window().maximize(); // Take everything on the page in list first . List<WebElement> completecalContent = driver.findElements(By.xpath("//*[@class='fk-display-block']")); System.out.println(completecalContent.size()); // printing all elements for (int i = 0; i < completecalContent.size(); i++) { System.out.println("Print complete Content : " + completecalContent.get(i).getText()); if (completecalContent.get(i).getText().equals("Apple iPhone 5S (Space Grey, 16 GB)")) { // move to a specific element ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", completecalContent.get(completecalContent.size() - 1)); // move slightly up as blue header comes in the picture ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,-100)"); // then click on the element completecalContent.get(i).click(); } } }
您要滾動的情況,在這種情況下,請使用這些行更新上面的代碼。
答:如果要滾動到頁面底部,則
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)");
B.如果您想滾動到特定元素,請嘗試此操作
WebElement element = driver.findElement(By.xpath("xpath to element"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView();", element);
C.如果要基於坐標滾動,請嘗試此操作
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");
除了向上滾動到Web元素外,您還可以嘗試向下滾動到類似頁面的頁面
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(250, 0)"); //x value '250' can be altered
否則,您可以嘗試滾動到足以勝過所需元素的元素。 這意味着在您嘗試的代碼中,沒有采用必需的web元素,而是僅滾動到所需元素上方的web元素,以便標頭不覆蓋必需元素。
謝謝,穆拉利
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.