如何在 Catalina 上使用带有 Selenium 的 Brave 网络浏览器?

How to use Brave web browser with Selenium on Catalina?

https://www.codegrepper.com/code-examples/python/python+selenium+brave+browser

我看到这个例子是在 windows 上使用勇敢的浏览器。它是否也应该通过替换 driver_path 和 brave_path 来在 Catalina 上工作?

此外,Chrome驱动程序仅适用于 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 网络驱动程序版本匹配。

为确保它确实如此:

  • brew info chromedriver 检查 ChromeDriver 版本。按照输出的顺序,它应该显示为 chromedriver: 89.0.4389.23(撰写本文时的最新版本 post)
  • 打开Brave Browser,在菜单栏点击Brave -> About Brave。沿着这条线它应该读作 Version 1.22.71 Chromium: 89.0.4389.114 (Official Build) (x86_64)(同样,写这篇文章时最新的 post)
  • 这两个应该匹配,但是,我不确定匹配到什么程度,因为正如您在此处看到的那样,最后的条目(.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, chrome_options=options)
browser.get("https://www.google.es")

如果您之前从未使用过 chromedriver,在 运行nning 代码后您应该看到 macOS 提示说 chromedriver 来自未知开发者或从互联网下载,那样的事关闭该提示(在继续之前执行此操作很重要)。然后转到 System Preferences -> Security & Privacy -> 按锁定图标解锁,然后在你的机器上批准 chromedriver 到 运行。 运行 再次执行上面的代码,又会出现一个新的 macOS 提示,说未知开发者,这次你可以点击打开。此时应该会弹出 Brave Browser window。至少在我的机器上是这样。
P.S。我为可能涉及太多细节而道歉,但有时我对跳过被认为 obvious[=28 的部分的答案感到非常沮丧=]

对于下一个正在寻找的人,这是在 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()