解答:如何使用Selenium控制已打开的Chrome浏览器窗口
大家好,我是本际云服务器推荐网的小编小本本。今天给大家分享一下如何使用Selenium控制已打开的Chrome浏览器窗口。

步骤一:手动打开浏览器并设置调试模式
首先,我们需要手动打开Chrome浏览器并设置调试模式。首先来到Chrome浏览器的安装文件夹下(例如:C:\Program Files (x86)\Google\Chrome\Application),在该界面打开命令提示符窗口(cmd)。接着输入以下命令:
chrome.exe --remote-debugging-port=9527 --user-data-dir="F:\selenium\AutomationProfile"
以上命令是启动Chrome浏览器的调试模式,--user-data-dirr="F:\selenium\AutomationProfile" 是在多带带的配置文件中启动Chrome浏览器,可创建对应文件夹。其中9527是自定义的端口号。
此时我们会发现,桌面上新打开了一个Chrome浏览器。
步骤二:编写Python程序控制浏览器窗口
接着,我们需要编写Python程序来控制这个手动打开的Chrome浏览器窗口。以下为示例代码:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_experimental_option("debuggerAddress", "127.0.0.1:9527")
browser = webdriver.Chrome(options=options)
url = 'https://www.bilibili.com'
browser.get(url)
print(browser.title)
以上代码可以获取当前打开页面的title。修改url参数即可获取不同页面的title。可以通过该程序实现自动登录需要输入手机验证码或人机验证的网站等应用场景。
总结
以上就是使用Selenium控制已打开的Chrome浏览器窗口的步骤。首先手动打开浏览器并设置调试模式,然后编写Python程序控制浏览器窗口。
感谢观看,希望这篇文章能够对大家有所帮助。如有其他问题,欢迎在评论区留言,小编会尽力解答。
原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/7232.html
