如何在wsl2上从python3运行Selenium ChromeDriver?

slhcrj9b  于 2023-07-01  发布在  Python
关注(0)|答案(4)|浏览(186)

我正在尝试使用Python 3从WSL 2(Ubuntu 18.04)无头打开Chrome。
在Windows上,我使用Chrome 84。我从ChromeDriver - WebDriver for Chrome下载了Chrome驱动程序84。并在C:\ChromeDriver\chromedriver.exe下安装了.exe
我已经设置了一个从Windows Chrome和ChromeDriver到WSL 2的符号链接:

sudo ln -s '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe' /usr/bin/google-chrome
sudo ln -s /mnt/c/ChromeDriver/chromedriver.exe /usr/bin/chromedriver

这两个Chrome都被设置为可由WSL 2上的任何用户执行。
在WSL 2上,当我在控制台中输入:

google-chrome --use-gl=swiftshader

Chrome在Windows上启动。
以下是我的脚本:

from selenium import webdriver
browser = webdriver.Chrome()    # fails
# browser = webdriver.Chrome('/usr/bin/chromedriver') fails
# browser = webdriver.Chrome('/mnt/c/ChromeDriver/chromedriver.exe') fails
browser.get('https://stackoverflow.com')

失败,错误:
raise WebDriverException(“Can not connect to the Service %s”% self.path)selenium.common.exceptions.WebDriverException:无法连接到服务chromedriver(* OR /usr/bin/chromedriver OR/mnt/c/ChromeDriver/chromedriver.exe取决于我如何启动webdriver.Chrome())
如何使用python3和selenium从WSL 2启动Chrome驱动程序?

brjng4g3

brjng4g31#

对于那些还没有找到解决方案的人。按照以下教程操作:chromedriver in WSL2许多都是类似的,但对我来说,诀窍是将chromedriver放在相应的组和用户中:

sudo chown root:root /usr/bin/chromedriver
ct2axkht

ct2axkht2#

你可以通过给定的代码安装chromedrive。

wget -N http://chromedriver.storage.googleapis.com/2.26/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
chmod +x chromedriver
sudo mv -f chromedriver /usr/local/share/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver

如果你没有使用给定的代码,你确实需要Chrome。

wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | sudo tee /etc/apt/sources.list.d/google-chrome.list
sudo apt-get update 
sudo apt-get install google-chrome-stable

我可能会错过一些东西,所以,请参阅参考网站。参考:https://www.srcmake.com/home/selenium-python-chromedriver-ubuntu
在你得到selenium和chrome驱动程序后,你可以使用给定的代码来实现无头chrome。另外,有一个软件包叫做“chromedriver_autoinstaller”,我不确定它是否能在ubuntu上工作,但如果你每天都使用相同的脚本,并且你的浏览器处于自动更新状态,它是一个很好的软件包。
headless chrome的代码:

#for headless browser use this arguments
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=1920x1080")
driver = webdriver.Chrome(chrome_options=chrome_options)

如果你使用路径和其他条件,在webdriver.chrome中输入必要的参数。

vyswwuz2

vyswwuz23#

我觉得这不可能你在Linux下,所以你不能使用Windows可执行文件。
我试着用了无头版的Chromium,但是不行,因为(看起来)Q

7fhtutme

7fhtutme4#

https://www.selenium.dev/documentation/grid/getting_started/
你可以用网格来解决这个问题
在Windows中:
1.安装驱动程序并配置路径
1.安装java 11或更高版本
1.安装selenium-server
在wsl 2-Ubuntu 20.04中:

  1. pip install selenium

相关问题