【发布时间】:2022-08-11 01:35:20
【问题描述】:
我正在尝试 dockerize 并运行使用 python 中的 selenium 库开发的网络抓取工具。我使用 Windows 10 进行开发。它在那里运行良好。在运行与 docker 映像相同的脚本时,我遇到了多个问题。这就是我在 Windows 中连接驱动程序的方式。
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
我没有使用选项,因为我没有任何用例。由于在 docker 中运行时出现 root 用户错误,我添加了该选项并运行如下代码。
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(\'--no-sandbox\')
driver = webdriver.Chrome(options = chrome_options, service=Service(ChromeDriverManager().install()))
尽管如此,它并没有开始。所以我通过硬编码驱动程序路径来配置它。
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(\'--no-sandbox\')
driver = webdriver.Chrome(executable_path=driverPath,options=option)
即使那样它也没有开始,因为没有配置显示。所以配置了无头参数并运行,但最后,我得到了以下错误。
**
Tkinter.TclError:没有显示名称,也没有 $DISPLAY 环境变量
**
所以我尝试通过下面的代码开始显示。
if platform.system() == \'Linux\': from pyvirtualdisplay import Display display = Display(visible=0, size=(800, 800)) display.start() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument(\'--no-sandbox\') driver = webdriver.Chrome(executable_path=driverPath,options=option)但它没有运行,它被冻结并且没有创建驱动程序会话。
这是我的 Dockerfile
FROM python RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \\ && echo \"deb http://dl.google.com/linux/chrome/deb/ stable main\" >> /etc/apt/sources.list.d/google.list RUN apt-get update && apt-get -y install google-chrome-stable RUN apt-get install -yqq unzip RUN wget -O /tmp/chromedriver.zip http://chromedriver.storage.googleapis.com/`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE`/chromedriver_linux64.zip RUN unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/ RUN apt-get install xvfb mesa-utils -y \\ && apt install freeglut3-dev -y ENV DISPLAY=:99 RUN mkdir -p /app/drivers ADD requirements.txt /app ADD sample.py /app COPY run.sh /app COPY drivers /app/drivers COPY csv /app/csv WORKDIR /app RUN pip3 install -r requirements.txt CMD ./run.sh运行.sh
#!/bin/sh #Xvfb :99 -screen 0 640x480x8 -nolisten tcp & python3 ./sample.py要求.txt
selenium==4.3.0 webdriver-manager==3.8.2 chromedriver-py==103.0.5060.53 pyvirtualdisplay==3.0我在代码中犯了什么错误?以及如何在 docker 中运行 selenium python 应用程序并显示?谢谢你。
-
您是否看到任何错误?
-
我没有看到任何错误。它被冻结了。在检查 bash 时,我看到 chrome 出现崩溃错误。
-
通常,当像这样运行 selenium 时,您希望使用headless mode,而不是尝试模拟虚拟显示器。无头模式设置起来更快、更容易。你能试试吗?
-
是的,我试过了,但我需要为某些目的显示。在无头模式下,我收到了这个错误。 Tkinter.TclError:没有显示名称,也没有 $DISPLAY 环境变量