一步到位的 Python 代码(Windows 双屏示例)
工作中使用双屏编写代码,开发工具放在主屏,浏览器放在副屏。
近日在使用 selenium 编写爬虫的时候,打开的浏览器窗口遮挡住了开发工具。
于是有了以下代码,selenium 调用浏览器的时候定位到副屏。
from selenium import webdriver # 导入 Selenium 的 WebDriver,用于操作浏览器
from selenium.webdriver.chrome.options import Options # 导入 Chrome 浏览器的配置类
import ctypes # 调用 Windows 原生 API 需要 ctypes
import subprocess # 这里没用到,可删掉(留给你备用)
import time # 这里也没用到,可删掉(留给你备用)
# ---------- 1. 找到副屏左上角坐标 ----------
def get_secondary_monitor_left():
"""返回副屏最左边的 x 坐标;如只有一块屏则返回 0"""
# 定义空列表,用来保存每个显示器的 (left, top, right, bottom)
monitors = []
# 定义一个回调函数,供 Win32 API 枚举显示器时调用
def _enum_proc(hMonitor, hdcMonitor, lprcMonitor, dwData):
r = lprcMonitor.contents # 取出 RECT 结构体
monitors.append((r.left, r.top, r.right, r.bottom)) # 记录坐标
return 1 # 返回非 0 表示继续枚举
# 定义回调函数原型(Win32 要求)
MONITORENUMPROC = ctypes.WINFUNCTYPE(
ctypes.c_int, # 返回值 int
ctypes.c_void_p, # 参数1: HMONITOR
ctypes.c_void_p, # 参数2: HDC
ctypes.POINTER(ctypes.wintypes.RECT), # 参数3: RECT*
ctypes.c_int) # 参数4: LPARAM
# 调用 Win32 API EnumDisplayMonitors,遍历所有显示器
ctypes.windll.user32.EnumDisplayMonitors(
0, 0, # 默认 DC,默认裁剪矩形
MONITORENUMPROC(_enum_proc), # 传入回调函数
0) # 自定义数据,这里不需要
# 如果只有一块显示器,直接返回 0
if len(monitors) < 2:
return 0
# 按 left 坐标升序排序,通常第 0 个是主屏
monitors.sort(key=lambda m: m[0])
# 返回副屏的最左边 x 坐标
return monitors[1][0]
# 调用函数,得到副屏左边的 x 值
second_left = get_secondary_monitor_left()
# ---------- 2. 启动浏览器 ----------
chrome_opts = Options() # 创建 Chrome 启动参数对象
chrome_opts.add_argument("--disable-blink-features=AutomationControlled") # 去掉“Chrome 正受到自动测试软件控制”的提示条
driver = webdriver.Chrome(options=chrome_opts) # 启动 Chrome 浏览器,并把上面参数传进去
# ---------- 3. 把窗口放到副屏 ----------
driver.set_window_position(second_left, 0) # 把浏览器左上角移到副屏左上角 (x=second_left, y=0)
driver.maximize_window() # 最大化浏览器,让它填满整个副屏
driver.get("https://www.bilibili.com") # 打开指定网址
time.sleep(10)
driver.quit()