文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Python中ghost的使用

2023-01-31 02:53

关注

ghost.py is a webkit web client written in python.

from ghost import Ghostghost = Ghost()page, extra_resources = ghost.open("http://jeanphi.fr")assert page.http_status==200 and 'jeanphix' in ghost.content

First you need to install either PyQt or PySide that are availables for many platforms.

Then you may install ghost.py using pip:

pip install Ghost.py

First of all, you need a instance of Ghost web client:

from ghost import Ghostghost = Ghost()

Ghost provide a method that open web page the following way:

page, resources = ghost.open('http://my.web.page')

This method returns a tuple of main resource (web page) and all loaded resources (such as CSS files, javascripts, images...).

All those resources are backed as HttpResource objects.

At the moment Httpresource objects provide the following attributes:

  • url: The resource url.
  • http_status: The HTTP response status code.
  • headers: The response headers as a dict.

Executing javascripts inside webkit frame is one of the most interesting features provided by Ghost:

result, resources = ghost.evaluate( "document.getElementById('my-input').getAttribute('value');")

The return value is a tuple of:

  • last javascript last statement result.
  • loaded resources (e.g.: when an XHR is fired up).

As many other Ghost methods, you can pass an extra parameter that tells Ghost you expect a page loading:

page, resources = ghost.evaluate( "document.getElementById('link').click();", expect_loading=True)

Then the result tuple wil be the same as the one returned by Ghost.open().

Fill a field

You can set a form field value trougth Ghost.set_field_value(selector, value, blur=True, expect_loading=False):

result, resources = ghost.set_field_value("input[name=username]", "jeanphix")

If you set optional parameter `blur` to False, the focus will be left on the field (usefull for autocomplete tests).

For filling file input field, simply pass file path as `value`.

Fill an entire form

You can fill entire form trougth Ghost.fill(selector, values, expect_loading=False):

result, resources = ghost.fill("form", { "username": "jeanphix", "password": "mypassword"})

Submit the form

Yon can submit the form by firing `submit` event:

page, resources = ghost.fire_on("form", "submit", expect_loading=True)

Ghost provides several methods for waiting for specific things before the script continue execution:

wait_for_alert()

That wait until a javascript alert() is send.

result, resources = ghost.wait_for_alert()

wait_for_page_loaded()

That wait until a new page is loaded.

page, resources = ghost.wait_for_page_loaded()

wait_for_selector(selector)

That wait until a element match the given selector.

result, resources = ghost.wait_for_selector("ul.results")

wait_for_text(text)

That wait until the given text exists inside the frame.

result, resources = ghost.wait_for_selector("My result")

Accept or deny javascript confirm is quite easy:

with Ghost.confirm(): # The confirm() box fired up by click will be accepted self.ghost.click('#confirm-button')with Ghost.confirm(False): # The confirm() box fired up by click will be denied self.ghost.click('#confirm-button')

Filling a value in prompt box:

with Ghost.prompt('my value'): # prompt() box fired up by click will be filled with 'my value' self.ghost.click('#prompt-button')

Ghost.capture_to(path, region=None, selector=None) method let's you take webkit current frame screenshots.

If you need to capture a specific region of the viewport, just provide a selector (or coordinates tuple) that feets your needs:

ghost.capture_to('header.png', selector="header")

Requirements:

pip install tornado

ghost.py provides a simple GhostTestCase that deals with WSGI applications:

import unittestfrom flask import Flaskfrom ghost import GhostTestCaseapp = Flask(__name__)@app.route('/')def home(): return 'hello world'class MyTest(GhostTestCase): port = 5000 @classmethod def create_app(cls): return app def test_open_home(self): self.ghost.open("http://localhost:%s/" % self.port) self.assertEqual(self.ghost.content, 'hello world')if __name__ == '__main__': unittest.main()

Debug your test

Tests can be run with a UI by setting display class member to True:

class MyTest(GhostTestCase): display = True

The following test tries to center http://www.openstreetmap.org/ map to France:

# Opens the web pageghost.open('http://www.openstreetmap.org/')# Waits for form search fieldghost.wait_for_selector('input[name=query]')# Fills the formghost.fill("#search_form", {'query': 'France'})# Submits the formghost.fire_on("#search_form", "submit")# Waits for results (an XHR has been called here)ghost.wait_for_selector( '#search_osm_nominatim .search_results_entry a')# Clicks first result linkghost.click( '#search_osm_nominatim .search_results_entry:first-child a')# Checks if map has moved to expected latitudelat, resources = ghost.evaluate("map.center.lat")assert float(lat.toString()) == 5860090.806537

Ghost provides an extension for django built on to of the upcoming LiveServerTestCase.

from ghost.ext.django.test import GhostTestCase
阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯