簡體   English   中英

硒:如何單擊JavaScript按鈕

[英]Selenium: how to click on javascript button

我必須編寫一些腳本進行自動測試,以檢查使用flex / amf技術構建的Web應用程序的加載時間。 該測試將包括打開IE瀏覽器,瀏覽多個選項卡並測量從單擊最后一個選項卡加載頁面內容到關閉瀏覽器所需的時間。

我在Java中使用Selenium Web Driver和Junit編寫了一個小腳本。 腳本打開IE窗口,輸入登錄名和密碼。 我有“單擊”登錄按鈕的問題。

首先,我嘗試通過findElement和By.partiallinktext查找並單擊按鈕,但是selenium通知我:“無法找到帶有部分鏈接文本的元素”(ctrl + f在該站點上工作正常)。

我嘗試使用moveByOffset鼠標單擊並單擊按鈕(在用密碼填充字符串后,類Robot-'tab'和'enter')單擊。 所有這些都不起作用。

接下來,我找到了JavascriptExecutor-我想這可能是我的問題的答案,但是我應該如何使用此類?

該網站上的按鈕:

<button style="width: 120px;" onclick="javascript:logIn();"> Login </button>

我的Java代碼:

WebElement button = driver.findElement(By.partialLinkText("Login")); 
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript ("document.getElementByText(\"Login\")).click();", button); 

我在測試方面經驗不足,因此,感謝您的幫助。

不要使用JavaScript。 嘗試這個:

String xPath = "//button[contains(.,'Login')]";
driver.findElement(By.xpath(xPath))).click();

更好,但未經測試:

// xPath to find a button whose text() (ie title) contains the word Login
String xPath = "//button[contains(text(),'Login')]";
driver.findElement(By.xpath(xPath))).click();

另請注意, https://sqa.stackexchange.com/具有有關Selenium(等)的信息。

按照您共享的HTML調用所需元素上的click() ,可以使用以下解決方案:

driver.findElement(By.xpath("//button[normalize-space()='Login']")).click();

從另一個角度看,所需元素看起來啟用了JavaScript ,在這種情況下,您必須誘使WebDriverWait使該元素可單擊,然后可以使用以下解決方案:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[normalize-space()='Login']"))).click();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM