Chrome 黑科技系列 - 操控运行中的浏览器给(男)女朋友惊喜!

1,347 阅读1分钟

大家好,我是泰斯特。在往期视频讲座 SeleniumConf - 测试秘技之远程实时操控浏览器 中 我们学习了如何使用 Chrome Devtools Protocol与运行中的浏览器进行通信。那么今天就来实践一下,如何通过 Chrome 给她(他)制造惊喜!

过程很简单,一共分为三个步骤。

(已通过亲身实践:)

第一步,以远程调试模式启动 Chrome 浏览器

mac 环境下终端运行下列命令:

sudo /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 --ignore-certificate-errors

windows 环境下终端运行下列命令:

chrome.exe --remote-debugging-port=9222 --ignore-certificate-errors

其中

  • --remote-debugging-port=9222 参数指定远程调试的端口为 9222;

  • --ignore-certificate-errors 参数忽略证书错误,方便后续操作。

第二步,准备定制化脚本

首先我们需要使用 Selenium 连接在第一步启动的浏览器

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options

# 连接远程浏览器
chrome_options = Options()



chrome_options.add_experimental_option(

                "debuggerAddress", "127.0.0.1:9222")



browser = Chrome(chrome_options=chrome_options,
                 executable_path='/usr/local/bin/chromedriver')

然后设置 5 分钟后弹出惊喜弹窗~

( 读者们可以在这一步自由发挥:)

# 过 5 分钟后,给它一个惊喜
import time
time.sleep(60 * 5)

# 惊喜在这里
browser.execute_script(script='alert("xxx,happy birthday~,love u 	3000 times~")')

设置好后可以直接运行脚本~

第三步,给她惊喜

这一步在实操中较为关键,

在前置步骤中我们准备好了浏览器与脚本。

万事俱备,只欠一部电影。

现在可以约她一起看个电影,

在观影过程中,惊喜会在预设的时间出现~