现在可以在带有自定义运行时的App Engine Flex上完成,所以我添加了这个答案,因为这个问题是谷歌弹出的第一件事.
我将这个自定义运行时基于我使用预构建的python运行时的其他GAE flex微服务
项目结构:
webdrivers/
- geckodriver
app.yaml
Dockerfile
main.py
requirements.txt
app.yaml中:
service: my-app-engine-service-name
runtime: custom
env: flex
entrypoint: gunicorn -b :$PORT main:app --timeout 180
Dockerfile:
FROM gcr.io/google-appengine/python
RUN apt-get update
RUN apt-get install -y xvfb
RUN apt-get install -y firefox
LABEL python_version=python
RUN virtualenv --no-download /env -p python
ENV VIRTUAL_ENV /env
ENV PATH /env/bin:$PATH
ADD requirements.txt /app/
RUN pip install -r requirements.txt
ADD . /app/
CMD exec gunicorn -b :$PORT main:app --timeout 180
requirements.txt:
Flask==0.12.2
gunicorn==19.7.1
selenium==3.13.0
pyvirtualdisplay==0.2.1
main.py
import os
import traceback
from flask import Flask, jsonify, Response
from selenium import webdriver
from pyvirtualdisplay import Display
app = Flask(__name__)
# Add the webdrivers to the path
os.environ['PATH'] += ':'+os.path.dirname(os.path.realpath(__file__))+"/webdrivers"
@app.route('/')
def hello():
return 'Hello!!'
@app.route('/test/', methods=['GET'])
def go_headless():
try:
display = Display(visible=0, size=(1024, 768))
display.start()
d = webdriver.Firefox()
d.get("http://www.python.org")
page_source = d.page_source.encode("utf-8")
d.close()
display.stop()
return jsonify({'success': True, "result": page_source[:500]})
except Exception as e:
print traceback.format_exc()
return jsonify({'success': False, 'msg': str(e)})
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
从这里下载geckodriver(linux 64):
其他说明:
>注意geckodriver,firefox和amp;的版本.您正在使用的selenium,因为它可以是finnickey,给出此错误WebDriverException:消息:无法加载配置文件.可能的firefox版本不匹配.您必须使用GeckoDriver代替Firefox 48.配置文件目录:/ tmp / tmp 48P如果在FirefoxBinary构造函数中指定了log_file,请检查它是否有详细信息.
>除非您使用遗留geckodriver / firefox,否则请勿设置DesiredCapabilities().FIREFOX [“marionette”] =假https://github.com/SeleniumHQ/selenium/issues/5106
> display =显示此错误需要显示(可见= 0,大小=(1024,768)):How to fix Selenium WebDriverException: The browser appears to have exited before we could connect?
要在本地测试:
docker build . -t my-docker-image-tag
docker run -p 8080:8080 --name=my-docker-container-name my-docker-image-tag
要部署到应用引擎:
gcloud app deploy app.yaml --version dev --project my-app-engine-project-id