问题很简单。我需要单击由 javascript 代码生成的弹出窗口中的一个元素。该页面仅在 IE 中可用,并且当开发人员工具打开时无法选择弹出窗口中的元素。基本上我不知道 xpath,但我确实有生成弹出窗口的 javascript。这是页面上的弹出窗口:
这是生成弹出窗口的 JavaScript 代码:
function pickDefaultType() {
// create popup
thePopup = window.createPopup();
var doc = thePopup.document;
var body = doc.body;
// add stylesheet
var oSheet = doc.createStyleSheet();
oSheet.addRule("TD", "cursor: hand; font-family: Verdana, Arial, sans-serif; font-size: " + $('body').css('font-size') + ";");
oSheet.addRule(".TableStyle", "overflow-y: auto; overflow-x: visible;");
oSheet.addRule(".DivStyle", "height: 100%; overflow-y: auto; overflow-x: visible; border: #C1D3E7 1px solid; color: #404040");
oSheet.addRule(".tableHeading", "background-color: #326894; color: white;");
// create scrolling div
var theDiv = thePopup.document.createElement("DIV");
theDiv.className = "DivStyle";
body.appendChild(theDiv);
theDiv.innerHTML = "<table cellpadding='2' cellspacing='0' width='100%' height='100%'><tr><td id='0'>" + sam.appStrings.defaultDateTypeNone + "</td><tr><tr><td id='1'>" + sam.appStrings.defaultDateTypeCurrent + "</td><tr><tr><td id='2'>" + sam.appStrings.defaultDateTypeOffset + "</td><tr><tr><td id='3'>" + sam.appStrings.defaultDateTypeFixed + "</td><tr></table>";
var theTable = theDiv.firstChild;
theTable.className = "TableStyle";
theTable.style.display = "";
theTable.onclick = selectDefaultType;
theTable.onmouseover = mouseOver;
theTable.onmouseout = mouseOut;
// deterine size to show the popup
thePopup.show(10, 10, 10, 10, typeSpan);
var tableWidth = theTable.offsetWidth + 18;
var tableHeight = theTable.offsetHeight + 2;
thePopup.show(0, typeSpan.clientHeight + 2, tableWidth, tableHeight, typeSpan);
}
我尝试使用 xpath 和 id 定位元素“None”,我也使用了 wait,例如
WebDriverWait wait = new WebDriverWait(webDriver, 3);
WebElement elem = wait.until(ExpectedConditions.elementToBeClickable(By.id("0")));
我还尝试了 Selenium 的 Alert 类:
Alert promptAlert = webDriver.switchTo().alert();
String alertText = promptAlert.getText();
System.out.println("Alert text is " + alertText);
找不到该元素。警报不存在。
如果弹出窗口位于框架中,我如何找到它的名称以切换到它?
请注意,我已经使用 Selenium 成功打开了下拉列表,只是找不到其中的元素来单击它们。
提前谢谢您!
最佳答案
有时,我们无法使用 webDriver 访问弹出窗口中的元素,在这种情况下,我们可以使用 JavascriptExecutor 来查找该元素。您似乎知道该元素的“Id”,请尝试以下代码来访问该元素。
WebElement ele =(WebElement) ((JavascriptExecutor)driver).executeScript("return document.getElementById("yourElementId"));
关于javascript - Selenium 在 javascript 弹出窗口中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39628677/