https://www.codegrepper.com/code-examples/python/python+selenium+brave+browser
我看到这个例子是在Windows上使用brave浏览器。只需替换 driver_path 和 Brave_path 就可以在 Catalina 上工作吗?
此外,Chromedriver 仅适用于 Chrome。如何确定brave浏览器应该使用哪个版本的chromedriver?
https://chromedriver.chromium.org
from selenium import webdriver
driver_path = "C:/Users/username/PycharmProjects/chromedriver.exe"
brave_path = "C:/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"
option = webdriver.ChromeOptions()
option.binary_location = brave_path
# option.add_argument("--incognito") OPTIONAL
# option.add_argument("--headless") OPTIONAL
# Create new Instance of Chrome
browser = webdriver.Chrome(executable_path=driver_path, chrome_options=option)
browser.get("https://www.google.es")
先决条件:
您的
chromedriver
版本应与您的 Brave Browser
Web 驱动程序版本相匹配。
为了确保它确实如此:
ChromeDriver
检查 brew info chromedriver
版本。沿着输出的行,它应该显示为 chromedriver: 89.0.4389.23
(撰写本文时的最新版本)Brave Browser
,在菜单栏中点击Brave
-> About Brave
。沿着这条线,它应该读作Version 1.22.71 Chromium: 89.0.4389.114 (Official Build) (x86_64)
(再次,截至撰写本文时最新).23
和.114
)不匹配,但这在我的机器上工作得很好( macOS Big Sur 11.2.3
)我认为 macOS 版本并不重要,但为了完整起见我仍然提到了它。最后运行以下代码(如果路径不同,请将路径替换为您机器上的路径):
from selenium import webdriver
driverPath = '/usr/local/Caskroom/chromedriver/89.0.4389.23/chromedriver'
binaryPath = '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'
options = webdriver.ChromeOptions()
options.binary_location = binaryPath
browser = webdriver.Chrome(executable_path=driverPath, options=options)
browser.get("https://www.google.com")
如果您之前从未使用过
chromedriver
,则运行代码后,您应该会看到 macOS 提示,指出 chromedriver
来自未知开发者或从互联网下载,诸如此类。关闭该提示(在继续之前执行此操作很重要)。然后转到 System Preferences
-> Security & Privacy
-> 按锁定图标并将其解锁,然后批准 chromedriver
在您的计算机上运行。再次运行上面的代码,会再次出现一个新的 macOS 提示,提示“未知开发者”,这次您只需单击“打开”即可。此时应该会弹出 Brave 浏览器窗口。至少在我的机器上是这样。对于下一个人来说,这是在 Mac 上使用 Brave 和 Selenium 的最新方式:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
driverPath = "/Applications/chromedriver" # Path to ChromeDriver
service = Service(driverPath)
options = webdriver.ChromeOptions()
options.binary_location = "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser" # Path to Brave Browser (this is the default)
driver = webdriver.Chrome(service=service, options=options)
# From here its Selenium as usual, example:
driver.get("https://google.com")
print(driver.title)
driver.close()