在Brave浏览器中使用Selenium传递用Python编写的服务对象

问题描述

#TLDR我想使用带有用python编写的Selenium的勇敢浏览器,但找不到任何当前可用的解决方案。

此代码正常工作

from selenium import webdriver
option = webdriver.ChromeOptions()
option.binary_location = r'C:Program FilesBraveSoftwareBrave- 
BrowserApplicationrave.exe'
driver = webdriver.Chrome(executable_path=r'C:WebDriverschromedriver.exe', 
options=option)
driver.get("https://www.google.com")
driver.quit()

但EXECUTABLE_PATH已弃用:

C:UsersUSERPycharmProjectspythonProjectsol2.py:5: 
DeprecationWarning: executable_path has been deprecated, please pass in a Service object 
driver = webdriver.Chrome(executable_path=r'C:WebDriverschromedriver.exe', options=option)

在YouTube上找到此内容:https://www.youtube.com/watch?v=VMzmVFA-Gps

# import statements
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# Declare variables and setup services
driverService = Service('C:/webdrivers/chromedriver.exe')   
# 1. Passes the chromedriver path to the service object
# 2. stores the service object in the s variable
driver = webdriver.Chrome(service=driverService)            
# 1. Passes service object s into the webdriver.Chrome  
# 2. Stores object in driver variable 

# Body (actually doing stuff)
driver.maximize_window()                # maximizes the browser window
driver.get("https://www.google.com")    # navigates to google.com
myPageTitle = driver.title              
# gets the title of the web page stores in myPageTitle
print(myPageTitle)                      # prints myPageTitle to Console
assert "Google" in myPageTitle          
# checks myPageTitle to ensure it contains Google

# clean up
driver.quit()                           # closes the browser

当我运行此代码时,我得到: selenium.common.exceptions.WebDriverException:消息:未知错误:找不到Chrome二进制文件

只要您允许将Google Chrome安装到您的PC上,此代码就可以运行。我不希望在我的电脑上使用Chrome。

问题是我想不出如何让Selenium使用Brave而不是Chrome。

在撰写本文时,我使用的是以下内容:
Windows 11主页
Selenium v4.0.0
Python V3.10
ChromeDriver 95.0.4638.69
Brave浏览器版本1.31.91 Chromium:95.0.4638.69(官方版本)(64位)

谁能解释一下如何在Brave Browser上使用当前(读取不建议使用的)代码来实现这一点吗?感谢您抽出时间。


解决方案

要启动brave浏览上下文,您需要:

  • 使用binary_location属性指向勇敢的二进制位置。
  • 使用chromedriver可执行文件启动BRAGE浏览器。

挡路代码:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

option = webdriver.ChromeOptions()
option.binary_location = r'C:Program Files (x86)BraveSoftwareBrave-BrowserApplicationrave.exe'
driverService = Service('C:/Users/.../chromedriver.exe')
driver = webdriver.Chrome(service=driverService, options=option)
driver.get("https://www.google.com")

注意:DeprecationWarning: executable_path has been deprecated是无害的警告消息,不会影响您的测试执行,您仍然可以忽略它。


引用

您可以在以下位置找到几个相关的详细讨论:

  • How to use Brave web browser with python, selenium and chromedriver?
  • How to initiate Brave browser using Selenium and Python on Windows

相关文章