Selenium:如何在 Chrome 和 Python 中处理 JNLP 问题

问题描述

在 Chrome(Edge 或 Firefox)中 JNLP 警告 当我尝试使用 Selenium WebDriver 打开包含此 Java 扩展的网页时,此类文件可能会损害您的计算机弹出窗口。有 2 个按钮 - Keep 允许继续,discard 以...丢弃。该警告禁止任何其他操作,因为可能无法允许 JNLP 并通过 Selenium 本身从浏览器运行其安装。一种可能的解决方案是使用不同的浏览器(或像 IE 这样的退役浏览器)或使用一些变通方法,例如下面的...

解决方法

使用 Python + Selenium 的解决方案
简短说明:在 win32api 和 win32con 的帮助下,单击保留按钮并下载文件。类似的方法或原理可用于其他编程语言或操作系统。

from selenium import webdriver
import time
import win32api,win32con

# define click action - click with left mouse button at a position
def click_at(coord):
    # move mouse cursor on requested position (coord is tuple with X and Y position)
    win32api.SetCursorPos(coord)
    # press and release LMB
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,coord[0],coord[1])
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,coord[1])

# set path to chromedriver and start as usually
chromeserver = r'...\chromedriver.exe'
driver = webdriver.Chrome(executable_path=chromeserver)
# run page containing JNLP
driver.get('http://somepagewithjnpl.com')

# maximize browser window 
driver.maximize_window()
# get size of the window via Selenium - returns dictionary {'width': int,'height': int}
# (note: 0;0 point is located to upper left corner)
current_size = driver.get_window_size()
# set coordinations where mouse should click on Keep button 
# (note: position could be slightly different in different browsers or languages - successfully 
# tested in Chrome + Win10 + Czech and English langs) 
coord = (current_size['width'] // 4,current_size['height']-50)
# click on Keep button to start downloading JNLP file
click_at(coord)
# take a short breather to give browser time to download JNLP file,notification changes then
time.sleep(5)

# set new coords and click at JNLP file to install and run Java WebStart
coord = (50,current_size['height']-50)
click_at(coord)
# center mouse cursor (not necessary but I like it)
coord = (current_size['width'] // 2,current_size['height'] // 2)
win32api.SetCursorPos(coord)
# take a breather again to give browser time for JNLP installation and Java activation
time.sleep(10)

恭喜 - 您现在应该站在丑陋的 JNLP 看门人后面,并且可以做任何您需要的事情。