栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

适用于GAE的Python Headless浏览器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

适用于GAE的Python Headless浏览器

现在,可以使用自定义运行时在App Engine Flex上完成此操作,因此我要添加此答案,因为此问题是在Google中弹出的第一件事。

我将此自定义运行时基于其他使用预先构建的python运行时的GAE flex微服务

项目结构:

webdrivers/- geckodriverapp.yamlDockerfilemain.pyrequirements.txt

app.yaml:

service: my-app-engine-service-nameruntime: customenv: flexentrypoint: gunicorn -b :$PORT main:app --timeout 180

Dockerfile:

FROM gcr.io/google-appengine/pythonRUN apt-get updateRUN apt-get install -y xvfbRUN apt-get install -y firefoxLABEL python_version=pythonRUN virtualenv --no-download /env -p pythonENV VIRTUAL_ENV /envENV PATH /env/bin:$PATHADD requirements.txt /app/RUN pip install -r requirements.txtADD . /app/CMD exec gunicorn -b :$PORT main:app --timeout 180

requirements.txt:

Flask==0.12.2gunicorn==19.7.1selenium==3.13.0pyvirtualdisplay==0.2.1

main.py

import osimport tracebackfrom flask import Flask, jsonify, Responsefrom selenium import webdriverfrom pyvirtualdisplay import Displayapp = Flask(__name__)# Add the webdrivers to the pathos.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.enpre("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):

https://github.com/mozilla/geckodriver/releases

其他说明:

  • 请注意您正在使用的geckodriver,firefox和selenium的版本,因为它可能是finnickey,出现此错误
    WebDriverException: Message: Can't load the profile. Possible firefox version mismatch. You must use GeckoDriver instead for Firefox 48+. Profile Dir: /tmp/tmp 48P If you specified a log_file in the FirefoxBinary constructor, check it for details.
  • 除非您使用旧版geckodriver / firefox,否则请勿设置
    DesiredCapabilities().FIREFOX["marionette"] = False
    https://github.com/SeleniumHQ/selenium/issues/5106
  • display = Display(visible=0, size=(1024, 768))
    需要修复此错误:如何修复Selenium WebDriverException:在连接之前,浏览器似乎已退出?

要在本地测试:

docker build . -t my-docker-image-tagdocker 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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624502.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号