一日一技:Selenium如何接管已经运行的Chrome浏览器?
source link: https://www.kingname.info/2021/12/23/remote-debug-selenium/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
一日一技:Selenium如何接管已经运行的Chrome浏览器?
在昨天的文章一日一技:爬虫模拟浏览器如何避免重复登录?中,我讲到了如何使用Puppeteer接管已经运行的Chrome。今天我们来讲讲使用Selenium如何实现这个功能。
在正式开始之前,先纠正昨天的一个错误。昨天我讲到,Windows电脑启动Chrome的远程调试模式用到的命令是:
文件路径/chrome.exe --remote-debugging-port=9222
这个地方漏掉了一个参数。正确的命令应该是:
文件路径/chrome.exe --remote-debugging-port=9222 --user-data-dir="某个存在的文件夹地址"
好了,回到正题。现在无论你使用macOS还是Windows,首先按昨天的文章所说,启动Chrome开放9222端口。然后,在这个Chrome中,手动登录示例网站。
接下来,编写下面这段代码:
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")
# 注意我把chromedriver文件放到了当前文件夹里面,所以可以这样调用
# 如果你是windows电脑,你需要使用./chromedriver.exe
driver = Chrome('./chromedriver', options=chrome_options)
driver.get('http://exercise.kingname.info/exercise_login_success')
input('输入任意内容继续')
driver.get('https://www.kingname.info')
input('输入任意内容继续')
driver.get('http://exercise.kingname.info/exercise_login_success')
如下图所示:
由于使用Selenium的时候,始终操作的都是当前标签页,为了证明确实有效,所以我在示例代码里面,先把爬虫暂停,需要你在终端按下任何键以后,再打开我的博客。接下来,等你确认博客已经打开以后,再回到终端按下任意键,Chrome会再次打开登录成功的页面。
你还可以试一试把Python程序终止,再重新运行。你会发现代码依然可以接管这个浏览器窗口。
Recommend
-
42
Matrix 精选 Matrix 是少数派的写作社区,我们主张分享真实的产品体验,有实用价值的经验与思考。我们会不定期挑选 Matrix 最优质的文章,展示来自用户的最真实的体验和观点。 文章代表作者个人观点,少数派仅对标...
-
27
Matrix 精选 Matrix 是少数派的写作社区,我们主张分享真实的产品体验,有实用价值的经验与思考。我们会不定期挑选 Matrix 最优质的文章,展示来自用户的最真实的体验和观点。 文章代表作者个人观点,少数...
-
20
摄影:产品经理 这个锅巴不好吃 Scrapy自带的 FilesPipeline
-
6
Matrix 首页推荐 Matrix 是少数派的写作社区,我们主张分享真实的产品体验,有实用价值的经验与思考。我们会不定期挑选 Matrix 最优质的文章,展示来自用户的最真实的体验和观点。 文章代表作者个人观点,少数派仅对标题...
-
6
一日一技:你真的知道如何设置环境变量? 发表于 2021-05-...
-
6
一日一技:Scrapy 如何正确 Post 发送 JSON 数据 发表于 2...
-
16
一日一技:爬虫模拟浏览器如何避免重复登录? 发表...
-
4
一日一技:如何阅读技术文档(直播文案) 发表于...
-
7
一日一技:macOS如何找回已经连接的Wi-Fi密码? 发...
-
4
一日一技:如何在浏览器中使用npm包? 发表于...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK