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

Selenium: how to handle JNLP issue in Chrome and Python

在 Chrome(Edge 或 Firefox)中 JNLP 警告 这种类型的文件可能会危害您的计算机 当我尝试打开包含此文件的网页时弹出窗口 Java 使用 Selenium WebDriver 扩展。有 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[0], 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 看门人后面,可以做任何您需要的事情。