> 文章列表 > selenium 连接已经打开的chrome浏览器 MAC

selenium 连接已经打开的chrome浏览器 MAC

selenium 连接已经打开的chrome浏览器 MAC

selenium 连接已经打开的chrome浏览器 MAC

一,前言

今天在爬取chatGPT的谷歌插件的prompts的时候,发现绕不过他的反爬机制,失败+1+1+1,所以想用连接已打开的chatGPT页面进行控制

二,具体步骤

1,添加环境变量

用临时在终端添加环境变量的方法,方便又快捷了属实是,新打开一个终端复制粘贴即可。

export PATH="/Applications/Google Chrome.app/Contents/MacOS:$PATH"
source ~/.bashrc

测试有没有添加环境变量成功:

echo $PATH

selenium 连接已经打开的chrome浏览器 MAC
当看到多了 /Applications/Google Chrome.app/Contents/MacOS就代表临时添加成功了。

2,启动Chrome调试模式

Google\\ Chrome --remote-debugging-port=9222 --user-data-dir="~/ChromeProfile"

运行这个后,就可以看见一个chrome打开了,接下来写程序连接它:

3,模版程序

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChainsoptions = webdriver.ChromeOptions()options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
# options.add_experimental_option('excludeSwitches', ['enable-automation'])
browser = webdriver.Chrome(executable_path=chromedriver_path, options=options)url='https://www.tmall.com/'browser.get(url)
# 这两个属性可以用来做断言使用
print("当前页面标题:", driver.title)
print("当前页面的url:", driver.current_url)

运行上面的代码,会发现它连接到你刚才打开的浏览器
并输出天猫和https://www.tmall.com/。
注:当get中的url,浏览器中没有打开的时候会自动打开该页面,当已打开的时候,则会自动链接。