经过几天不睡觉,我终于明白了。
首先,我运行的是阿尔卑斯版的Ubuntu。这是第一个问题。但我成功了。所以,如果你们也在运行Alpine,这就是解决方案:
Dockerfile
FROM python:3.6.6-alpine3.8
# Project files
ARG PROJECT_DIR=/srv
RUN mkdir -p $PROJECT_DIR
WORKDIR $PROJECT_DIR
# Install Python dependencies
COPY ./ ./
RUN apk update
RUN apk add curl
RUN apk add unzip nano bash chromium chromium-chromedriver
RUN pip3 install -r requirements.txt
整个魔法就是安装铬。
现在是我们的*。py看起来像这样:
mobile_emulation = {"deviceName": "iPhone X"}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
#chrome_options.add_argument('--disable_infobars')
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', options=chrome_options)
driver.get('https://google.com')
奖金
.
我想用不同的
chromedriver
决定阿尔卑斯山真的把事情搞砸了。用python安装了合适的ubuntu并使chromedriver正常工作。下面是它的外观:
Dockerfile
FROM ubuntu:18.04
# Project files
ARG PROJECT_DIR=/srv
RUN mkdir -p $PROJECT_DIR
WORKDIR $PROJECT_DIR
# Update
RUN apt-get update
RUN apt-get -y upgrade
# Set the locale
RUN apt-get install -y locales && locale-gen "en_US.UTF-8" && dpkg-reconfigure -f noninteractive locales
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
ENV PYTHONIOENCODING utf-8
RUN echo \
&& echo 'LANG=en_US.UTF-8' >> /etc/environment \
&& echo 'LANGUAGE=en_US:en' >> /etc/environment \
&& echo 'LC_ALL=en_US.UTF-8' >> /etc/environment \
&& echo 'PYTHONIOENCODING=utf-8' >> /etc/environment
# Install Python dependencies
RUN apt-get install --upgrade -y python3-pip
RUN apt-get install -y build-essential libssl-dev libffi-dev python3-dev
RUN apt-get install -y curl
RUN apt-get install -y unzip
# Copy everything to Docker
COPY ./ ./
# Install chromium instead
RUN apt-get install -y chromium-browser
# Install chromedriver for Chromium
RUN curl https://chromedriver.storage.googleapis.com/75.0.3770.140/chromedriver_linux64.zip -o /usr/local/bin/chromedriver.zip
RUN unzip /usr/local/bin/chromedriver.zip -d /usr/local/bin/
RUN chmod +x /usr/local/bin/chromedriver || rm /usr/local/bin/chromedriver.zip
RUN pip3 install -r requirements.txt
我们的代码如下所示:
mobile_emulation = {"deviceName": "iPhone X"}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
#chrome_options.add_argument('--disable_infobars')
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', options=chrome_options)
driver.get('https://google.com')
driver.close()