脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 使用Selenium控制当前已经打开的chrome浏览器窗口

使用Selenium控制当前已经打开的chrome浏览器窗口

2022-07-07 10:15是小菜欸 Python

有时通过selenium打开网站时,发现有些网站需要扫码登录,就很头疼,导致爬虫进展不下去,下面这篇文章主要给大家介绍了关于使用Selenium控制当前已经打开的chrome浏览器窗口的相关资料,需要的朋友可以参考下

前言

有过几个小伙伴问过我如何利用 Selenium 获取已经打开的浏览器窗口,正巧近日看到有文章写到,我就很不要脸的拿来过拼凑到一起了。

这里使用 chrome浏览器 来做示例。

整个下来主要有两个步骤,

  • 手动打开浏览器,
  • 使用 Python程序 去获取到手动打开的 chrome浏览器

应用场景(理论上)

  • 登录账号并且需要输入手机验证码的网站;
  • 登录账号并且需要人机验证的网站(如图片点选、文字点选等人机验证;

1. 打开浏览器

首先来到安装 chrome浏览器 的文件夹下,例:C:Program Files (x86)GoogleChromeApplication

使用Selenium控制当前已经打开的chrome浏览器窗口

在此界面打开 cmd窗口,

然后输入:chrome.exe --remote-debugging-port=9527 --user-data-dir=“F:seleniumAutomationProfile” ,并回车。
这句代码的意思是启动 chrome浏览器 的调试模式,

  • user-data-dirr=“F:seleniumAutomationProfile” 是在单独的配置文件中启动 chrome浏览器,可以理解为 新的浏览器,记得创建对应文件夹哦;
  • 其中 9527 为端口号,可自行指定。

使用Selenium控制当前已经打开的chrome浏览器窗口

此时候,如果无误的话就可以看到桌面新打开了一个 chrome 浏览器了。

见以下示例动图,

使用Selenium控制当前已经打开的chrome浏览器窗口

那接下来就是去控制这个 手动打开的 chrome浏览器 啦。

2. 编写 Python程序获取控制 浏览器

Demo代码 如下:

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)

print(browser.title)

代码运行后,可以看到如下:即获取 当前页面的 title

使用Selenium控制当前已经打开的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)	# 哔哩哔哩 (゜-゜)つロ 干杯~-bilibili

运行之后可以看到,浏览器窗口请求了新的 URL(https://www.bilibili.com),并且获取到了当前页面的 title

使用Selenium控制当前已经打开的chrome浏览器窗口

3. 总结

去到 chrome浏览器 安装的文件夹下,打开 cmd窗口,输入以下内容:

chrome.exe --remote-debugging-port=9527 --user-data-dir="F:seleniumAutomationProfile"

然后执行 2.Python代码即可控制当前浏览器窗口。

后话

自己动手操作一番,岂不美哉?

到此这篇关于使用Selenium控制当前已经打开的chrome浏览器窗口的文章就介绍到这了,更多相关Selenium控制已打开浏览器窗口内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文地址:https://blog.csdn.net/weixin_45081575/article/details/112621581

延伸 · 阅读

精彩推荐