这两天被定位窗口的问题搞得焦头烂额,今天终于解决了。现记录如下:
关键字:弹窗 模态对话框 js autoit
问题:
def switch_to_win(driver, uimethod, uipath ):
#method value have name/id/xpath/class;webdriver is the driver you use
if uipath=='':
print('you must input the xpath')
else:
if uimethod=='title' or uimethod=='Title':#根据控件元素的titel属性定位窗口
all_handles = driver.window_handles #获取所有窗口句柄
for handle in all_handles:
driver.switch_to_window(handle)
if title == str(uipath):
print("当前窗口:{0}".format(title))
break
elif uimethod=='url' or uimethod=='URL' or uimethod=='Url':#根据控件元素的url属性定位窗口
all_handles = driver.window_handles #获取所有窗口句柄
for handle in all_handles:
driver.switch_to_window(handle)
url = str(driver.current_url)
if url == str(uipath):
print("当前窗口:{0}".format(url))
break
通过以上函数能成功定位新打开的窗口,单始终定位不到模态对话框,通过autoinfo工具查看对话框class为“Internet Explorer_TridentDlgFrame”
解决方法一:调用执行js(NG)
有网友说将点击链接的动作通过js来实现能解决问题,我也做了一翻尝试,但仍定位不到模态对话框
elif optype == "执行js":
driver.execute_script(uivalue)
解决方法二:借助AutoI工具(ok)
<span style="font-size:12px;">;filename:testopenwin.au3
;Dim $selectname = $CmdLine[1] ;加参数运行,如:testopenwin.exe "system"----system为参数1
Dim $selectname = "system"
If WinExists("[CLASS:Internet Explorer_TridentDlgFrame]") Then
WinWaitActive("[CLASS:Internet Explorer_TridentDlgFrame]")
Sleep(1*1000)
Send("{TAB}")
Sleep(500)
Send("{TAB}")
Sleep(500)
Send($selectname)
Sleep(1*1000)
Send("{ENTER}")
Sleep(500)
Send("{TAB}")
Sleep(500)
Send("{TAB}")
Sleep(500)
Send("{SPACE}");选中单选框
Sleep(500)
Send("{TAB}")
Sleep(500)
Send("{ENTER}")
$h=WinGetHandle("[CLASS:Internet Explorer_TridentDlgFrame]");获取句柄
ConsoleWrite($h);写入标准输出流,供python使用
EndIf
</span>
<span style="font-size:12px;"></span><pre name="code" class="plain">
#python脚本elif optype == "调用可执行文件":#os.system(uivalue) #uivalue中为 testopenwin.exe的路径output = os.popen(uivalue)print(output.read()) #out.read()返回ConsoleWrite函数的输出流
解决方法三:修改代码(ok)
修改代码,借鉴了他人的代码成功解决了问题。但以前的代码为什么行不通仍没找到原因!
def switch_to_win(driver, uimethod, uipath ):
currentWindow = driver.current_window_handle
for handle in driver.window_handles:
if handle != currentWindow:
newWindow = handle
if newWindow != '':
driver.switch_to_window(newWindow)
print(driver.title)
如果那位网友清楚的话,请多多赐教,谢谢~