Nightmare中文文檔(機器翻譯)


Build Status
Join the chat at https://gitter.im/rosshinkley/nightmare

Nightmare

Nightmare is a high-level browser automation library from Segment.

The goal is to expose a few simple methods that mimic user actions (like goto, type and click), with an API that feels synchronous for each block of scripting, rather than deeply nested callbacks. It was originally designed for automating tasks across sites that don't have APIs, but is most often used for UI testing and crawling.

Under the covers it uses Electron, which is similar to PhantomJS but roughly twice as fast and more modern.

⚠️ Security Warning: We've implemented many of the security recommendations outlined by Electron to try and keep you safe, but undiscovered vulnerabilities may exist in Electron that could allow a malicious website to execute code on your computer. Avoid visiting untrusted websites.

🛠 Migrating to 3.x: You'll want to check out this issue before upgrading. We've worked hard to make improvements to nightmare while limiting the breaking changes and there's a good chance you won't need to do anything.

Niffy is a perceptual diffing tool built on Nightmare. It helps you detect UI changes and bugs across releases of your web app.

Daydream is a complementary chrome extension built by @stevenmiller888 that generates Nightmare scripts for you while you browse.

Many thanks to @matthewmueller and @rosshinkley for their help on Nightmare.

Nightmare是[Segment](https://segment.com)中的高級瀏覽器自動化庫。

我們的目標是公開一些模仿用戶操作的簡單方法(例如goto,type和click),並提供一個針對每個腳本塊都是同步的API,而不是嵌套嵌套的回調。它最初設計用於在沒有API的站點之間自動執行任務,但是最常用於UI測試和爬網。

在幕后,它使用[Electron](http://electron.atom.io/),與[PhantomJS](http://phantomjs.org/)類似,但速度大約是[兩倍] github.com/segmentio/nightmare/issues/484#issuecomment-184519591)和更現代的版本。

⚠️安全警告:我們已經實施了[由Electron概述的]安全建議的[許多](https://github.com/segmentio/nightmare/issues/1388)(https://github.com/electron/electron/blob/master/docs/tutorial/security.md)來嘗試確保您的安全,但是Electron中可能存在未發現的漏洞,該漏洞可能允許惡意網站在您的計算機上執行代碼。避免訪問不受信任的網站。

🛠遷移到3.x:升級前,您想查看[此問題](https://github.com/segmentio/nightmare/issues/1396)。我們一直在努力改善噩夢,同時又限制了重大變化,因此您很有可能不需要做任何事情。

[Niffy](https://github.com/segmentio/niffy)是建立在噩夢基礎上的一種感知差異工具。它可以幫助您檢測Web應用程序發行版之間的UI更改和錯誤。

[Daydream](https://github.com/segmentio/daydream)是由[@ stevenmiller888](https://github.com/stevenmiller888)構建的一個互補chrome擴展,它在您瀏覽時為您生成Nightmare腳本。

非常感謝[@matthewmueller](https://github.com/matthewmueller)和[@rosshinkley](https://github.com/rosshinkley)在噩夢方面的幫助。

Examples

Let's search on DuckDuckGo:
讓我們搜索DuckDuckGo:

const Nightmare = require('nightmare')
const nightmare = Nightmare({ show: true })

nightmare
  .goto('https://duckduckgo.com')
  .type('#search_form_input_homepage', 'github nightmare')
  .click('#search_button_homepage')
  .wait('#r1-0 a.result__a')
  .evaluate(() => document.querySelector('#r1-0 a.result__a').href)
  .end()
  .then(console.log)
  .catch(error => {
    console.error('Search failed:', error)
  })

You can run this with:你可以運行這個:

npm install --save nightmare
node example.js

Or, let's run some mocha tests:或者,讓我們運行一些摩卡測試:

const Nightmare = require('nightmare')
const chai = require('chai')
const expect = chai.expect

describe('test duckduckgo search results', () => {
  it('should find the nightmare github link first', function(done) {
    this.timeout('10s')

    const nightmare = Nightmare()
    nightmare
      .goto('https://duckduckgo.com')
      .type('#search_form_input_homepage', 'github nightmare')
      .click('#search_button_homepage')
      .wait('#links .result__a')
      .evaluate(() => document.querySelector('#links .result__a').href)
      .end()
      .then(link => {
        expect(link).to.equal('https://github.com/segmentio/nightmare')
        done()
      })
  })
})

You can see examples of every function in the tests here.

To get started with UI Testing, check out this quick start guide.
你可以在這里看到測試中每個函數的例子。要開始使用UI測試,請查看本快速入門指南。

To install dependencies安裝依賴關系

npm install

To run the mocha tests運行摩卡測試

npm test

Node versions

Nightmare is intended to be run on NodeJS 4.x or higher.
Nightmare在運行在NodeJS 4.x或更高版本上。

API

Nightmare(options)

Creates a new instance that can navigate around the web. The available options are documented here, along with the following nightmare-specific options.
創建一個可以在網絡中導航的新實例。這里記錄可用的選項,以及以下Nightmare特定的選項。

waitTimeout (default: 30s)

Throws an exception if the .wait() didn't return true within the set timeframe.
如果.wait()在設定的時間內沒有返回true,則會引發異常。waitTimeout(默認:30秒)

const nightmare = Nightmare({
  waitTimeout: 1000 // in ms
})
gotoTimeout (default: 30s)

Throws an exception if the .goto() didn't finish loading within the set timeframe. Note that, even though goto normally waits for all the resources on a page to load, a timeout exception is only raised if the DOM itself has not yet loaded.
如果.goto()未在設定的時間范圍內完成加載,則會引發異常。請注意,即使goto正常等待頁面上的所有資源加載,只有當DOM本身尚未加載時才會引發超時異常。
gotoTimeout(默認:30秒)

const nightmare = Nightmare({
  gotoTimeout: 1000 // in ms
})
loadTimeout (default: infinite)

Forces Nightmare to move on if a page transition caused by an action (eg, .click()) didn't finish within the set timeframe. If loadTimeout is shorter than gotoTimeout, the exceptions thrown by gotoTimeout will be suppressed.
如果由動作引起的頁面轉換(例如,.click())未在設定的時間范圍內完成,則強制“nightmare”繼續前進。如果loadTimeout比gotoTimeout短,gotoTimeout拋出的異常將被抑制。
loadTimeout(默認:無限)

const nightmare = Nightmare({
  loadTimeout: 1000 // in ms
})
executionTimeout (default: 30s)

The maximum amount of time to wait for an .evaluate() statement to complete.
等待執行.evaluate()語句完成的最長時間。

const nightmare = Nightmare({
  executionTimeout: 1000 // in ms
})
paths

The default system paths that Electron knows about. Here's a list of available paths: https://github.com/atom/electron/blob/master/docs/api/app.md#appgetpathname

You can overwrite them in Nightmare by doing the following:
Electron知道的默認系統路徑。以下是可用路徑的列表:https://github.com/atom/electron/blob/master/docs/api/app.md#appgetpathname
您可以通過執行以下操作在“Nightmare”中覆蓋它們:

const nightmare = Nightmare({
  paths: {
    userData: '/user/data'
  }
})
switches

The command line switches used by the Chrome browser that are also supported by Electron. Here's a list of supported Chrome command line switches:
https://github.com/atom/electron/blob/master/docs/api/chrome-command-line-switches.md
Chrome瀏覽器使用的命令行開關也支持Electron。以下是支持的Chrome命令行開關列表:https://github.com/atom/electron/blob/master/docs/api/chrome-command-line-switches.md

const nightmare = Nightmare({
  switches: {
    'proxy-server': '1.2.3.4:5678',
    'ignore-certificate-errors': true
  }
})
electronPath

The path to the prebuilt Electron binary. This is useful for testing on different versions of Electron. Note that Nightmare only supports the version on which this package depends. Use this option at your own risk.
預建的Electron二進制文件的路徑。這對於在不同版本的Electron上進行測試很有用。請注意,nightmare只支持這個包依賴的版本。使用此選項需要您自擔風險。

const nightmare = Nightmare({
  electronPath: require('electron')
})
dock (OS X)

A boolean to optionally show the Electron icon in the dock (defaults to false). This is useful for testing purposes.
一個布爾值,可選擇在dock顯示Electron圖標(默認為false)。這對於測試目的很有用。

const nightmare = Nightmare({
  dock: true
})
openDevTools

Optionally shows the DevTools in the Electron window using true, or use an object hash containing mode: 'detach' to show in a separate window. The hash gets passed to contents.openDevTools() to be handled. This is also useful for testing purposes. Note that this option is honored only if show is set to true.
可以選擇使用true在Electron窗口中顯示DevTools,或使用包含對象哈希模式:'detach'在單獨的窗口中顯示。散列被傳遞給contents.openDevTools()進行處理。這對於測試目的也很有用。請注意,只有show設置為true時,此選項才有效。

const nightmare = Nightmare({
  openDevTools: {
    mode: 'detach'
  },
  show: true
})
typeInterval (default: 100ms)

How long to wait between keystrokes when using .type().
使用.type()時按鍵間的等待時間。

const nightmare = Nightmare({
  typeInterval: 20
})
pollInterval (default: 250ms)

How long to wait between checks for the .wait() condition to be successful.
檢查.wait()條件是否成功需要等待多長時間。

const nightmare = Nightmare({
  pollInterval: 50 //in ms
})
maxAuthRetries (default: 3)

Defines the number of times to retry an authentication when set up with .authenticate().
定義使用.authenticate()進行設置時重試認證的次數。

const nightmare = Nightmare({
  maxAuthRetries: 3
})

certificateSubjectName

A string to determine the client certificate selected by electron. If this options is set, the select-client-certificate event will be set to loop through the certificateList and find the first certificate that matches subjectName on the electron Certificate Object.
用於確定electron選擇的客戶端證書的字符串。如果設置了此選項,則select-client-certificate事件將設置為循環遍歷certificateList,並找到與electron證書對象上的subjectName匹配的第一個證書。

const nightmare = Nightmare({
  certificateSubjectName: 'tester'
})

.engineVersions()

Gets the versions for Electron and Chromium.
獲取Electron和Chromium的版本。

.useragent(useragent)

Sets the useragent used by electron.
設置electron使用的用戶代理。

.authentication(user, password)

Sets the user and password for accessing a web page using basic authentication. Be sure to set it before calling .goto(url).
使用基本身份驗證設置訪問網頁的用戶和密碼。請務必在調用.goto(url)之前進行設置。

.end()

Completes any queue operations, disconnect and close the electron process. Note that if you're using promises, .then() must be called after .end() to run the .end() task. Also note that if using an .end() callback, the .end() call is equivalent to calling .end() followed by .then(fn). Consider:
完成任何隊列操作,斷開並關閉electron進程。請注意,如果您使用承諾,則必須在.end()之后調用.then()才能運行.end()任務。另請注意,如果使用.end()回調,則.end()調用等同於調用.end()后跟.then(fn)。考慮:

nightmare
  .goto(someUrl)
  .end(() => 'some value')
  //prints "some value"
  .then(console.log)

.halt(error, done)

Clears all queued operations, kills the electron process, and passes error message or 'Nightmare Halted' to an unresolved promise. Done will be called after the process has exited.
清除所有排隊的操作,殺死electron進程,並將錯誤消息或'nightmare停止'傳遞給未解決的承諾。完成后將在完成后調用完成。

Interact with the Page 頁面交互

.goto(url[, headers])

Loads the page at url. Optionally, a headers hash can be supplied to set headers on the goto request.

When a page load is successful, goto returns an object with metadata about the page load, including:
根據url加載頁面。可選地,可以提供頭部哈希以在goto請求上設置頭部。當頁面加載成功時,goto返回一個包含頁面加載元數據的對象,其中包括:

  • url: The URL that was loaded
  • code: The HTTP status code (e.g. 200, 404, 500)
  • method: The HTTP method used (e.g. "GET", "POST")
  • referrer: The page that the window was displaying prior to this load or an empty string if this is the first page load.
  • headers: An object representing the response headers for the request as in {header1-name: header1-value, header2-name: header2-value}

If the page load fails, the error will be an object with the following properties:
如果頁面加載失敗,則該錯誤將是具有以下屬性的對象:

Note that any valid response from a server is considered “successful.” That means things like 404 “not found” errors are successful results for goto. Only things that would cause no page to appear in the browser window, such as no server responding at the given address, the server hanging up in the middle of a response, or invalid URLs, are errors.

You can also adjust how long goto will wait before timing out by setting the gotoTimeout option on the Nightmare constructor.
請注意,來自服務器的任何有效響應都被視為“成功”。這意味着404“找不到”錯誤是goto的成功結果。只有那些不會導致頁面出現在瀏覽器窗口中的東西,比如沒有服務器響應給定的地址,響應中間掛起的服務器或無效的URL都是錯誤。您還可以通過在Nightmare構造函數中設置gotoTimeout選項來調整goto在超時之前等待的時間。

.back()

Goes back to the previous page.
回到上一頁。

.forward()

Goes forward to the next page.
轉到下一頁。

.refresh()

Refreshes the current page.
刷新當前頁面。

.click(selector)

Clicks the selector element once.
單擊選擇器元素一次。

.mousedown(selector)

Mousedowns the selector element once.
Mousedowns選擇元素一次。

.mouseup(selector)

Mouseups the selector element once.
將鼠標移到選擇元素一次。

.mouseover(selector)

Mouseovers the selector element once.
將鼠標移到選擇元素一次。

.mouseout(selector)

Mouseout the selector element once.
將鼠標移出選擇元素一次。

.type(selector[, text])

Enters the text provided into the selector element. Empty or falsey values provided for text will clear the selector's value.

.type() mimics a user typing in a textbox and will emit the proper keyboard events.

Key presses can also be fired using Unicode values with .type(). For example, if you wanted to fire an enter key press, you would write .type('body', '\u000d').
輸入提供給選擇器元素的文本。為文本提供的空值或偽值將清除選擇器的值。
.type()模仿在文本框中輸入的用戶,並發出正確的鍵盤事件。
按鍵也可以使用.type()的Unicode值進行觸發。例如,如果您想按下回車鍵,則會寫入.type('body','\ u000d')。

If you don't need the keyboard events, consider using .insert() instead as it will be faster and more robust.
如果您不需要鍵盤事件,請考慮使用.insert(),因為它會更快更健壯。

.insert(selector[, text])

Similar to .type(), .insert() enters the text provided into the selector element. Empty or falsey values provided for text will clear the selector's value.

.insert() is faster than .type() but does not trigger the keyboard events.
類似於.type(),.insert()輸入提供給selector元素的文本。為文本提供的空值或偽值將清除選擇器的值。.insert()比.type()快,但不會觸發鍵盤事件。

.check(selector)

Checks the selector checkbox element.
檢查選擇器復選框元素。

.uncheck(selector)

Unchecks the selector checkbox element.
取消選中復選框元素。

.select(selector, option)

Changes the selector dropdown element to the option with attribute [value=option]
將選擇器下拉元素更改為屬性為[value = option]的選項

.scrollTo(top, left)

Scrolls the page to desired position. top and left are always relative to the top left corner of the document.
將頁面滾動到所需的位置。
頂部和左側總是相對於文檔的左上角。

.viewport(width, height)

Sets the viewport size.
設置視口大小。

.inject(type, file)

Injects a local file onto the current page. The file type must be either js or css.
將本地文件注入當前頁面。文件類型必須是js或css。

.evaluate(fn[, arg1, arg2,...])

Invokes fn on the page with arg1, arg2,.... All the args are optional. On completion it returns the return value of fn. Useful for extracting information from the page. Here's an example:
在頁面上用arg1,arg2,...調用fn。所有參數都是可選的。
完成后返回fn的返回值。
用於從頁面提取信息。
這是一個例子:

const selector = 'h1'
nightmare
  .evaluate(selector => {
    // now we're executing inside the browser scope.
    return document.querySelector(selector).innerText
  }, selector) // <-- that's how you pass parameters from Node scope to browser scope
  .then(text => {
    // ...
  })

Error-first callbacks are supported as a part of evaluate(). If the arguments passed are one fewer than the arguments expected for the evaluated function, the evaluation will be passed a callback as the last parameter to the function. For example:
作為evaluate()的一部分支持Error-first回調。
如果傳遞的參數少於預期的評估函數的參數,評估將作為函數的最后一個參數傳遞回調。

const selector = 'h1'
nightmare
  .evaluate((selector, done) => {
    // now we're executing inside the browser scope.
    setTimeout(
      () => done(null, document.querySelector(selector).innerText),
      2000
    )
  }, selector)
  .then(text => {
    // ...
  })

Note that callbacks support only one value argument (eg function(err, value)). Ultimately, the callback will get wrapped in a native Promise and only be able to resolve a single value.

Promises are also supported as a part of evaluate(). If the return value of the function has a then member, .evaluate() assumes it is waiting for a promise. For example:
請注意,回調僅支持一個值參數(例如,函數(err,value))。
最終,回調將被包裝在原生Promise中,並且只能解析單個值。
作為evaluate()的一部分,承諾也被支持。
如果函數的返回值有一個then成員,則.evaluate()假定它正在等待承諾。
例如:

const selector = 'h1';
nightmare
  .evaluate((selector) => (
    new Promise((resolve, reject) => {
      setTimeout(() => resolve(document.querySelector(selector).innerText), 2000);
    )}, selector)
  )
  .then((text) => {
    // ...
  })

.wait(ms)

Waits for ms milliseconds e.g. .wait(5000).
等待ms毫秒,例如

.wait(selector)

Waits until the element selector is present e.g. .wait('#pay-button').
等待直到元素選擇器存在為止,例如

.wait(fn[, arg1, arg2,...])

Waits until the fn evaluated on the page with arg1, arg2,... returns true. All the args are optional. See .evaluate() for usage.
等到fn在頁面上用arg1,arg2,...返回true評估為止。
所有的參數都是可選的。
請參閱.evaluate()以了解使用情況。

.header(header, value)

Adds a header override for all HTTP requests. If header is undefined, the header overrides will be reset.
為所有HTTP請求添加標頭覆蓋。
如果頭未定義,頭覆蓋將被重置。

Extract from the Page從頁面中提取

.exists(selector)

Returns whether the selector exists or not on the page.
返回頁面上是否存在選擇器。

.visible(selector)

Returns whether the selector is visible or not.
返回選擇器是否可見。

.on(event, callback)

Captures page events with the callback. You have to call .on() before calling .goto(). Supported events are documented here.
用回調捕獲頁面事件。
您必須在調用.goto()之前調用.on()。
這里記錄了受支持的事件。

Additional "page" events額外的“頁面”事件
.on('page', function(type="error", message, stack))

This event is triggered if any javascript exception is thrown on the page. But this event is not triggered if the injected javascript code (e.g. via .evaluate()) is throwing an exception.
如果在頁面上拋出任何javascript異常,則觸發此事件。
但是,如果注入的JavaScript代碼(例如通過.evaluate())拋出異常,則不會觸發此事件。

"page" events

Listens for window.addEventListener('error'), alert(...), prompt(...) & confirm(...).

.on('page', function(type="error", message, stack))

Listens for top-level page errors. This will get triggered when an error is thrown on the page.
偵聽頂級頁面錯誤。
這會在頁面上發生錯誤時觸發。

.on('page', function(type="alert", message))

Nightmare disables window.alert from popping up by default, but you can still listen for the contents of the alert dialog.
Nightmare將禁用window.alert默認彈出,但仍然可以偵聽警報對話框的內容。

.on('page', function(type="prompt", message, response))

Nightmare disables window.prompt from popping up by default, but you can still listen for the message to come up. If you need to handle the confirmation differently, you'll need to use your own preload script.
Nightmare使得window.prompt默認不彈出,但你仍然可以聽到消息出現。
如果您需要以不同方式處理確認,則需要使用自己的預加載腳本。

.on('page', function(type="confirm", message, response))

Nightmare disables window.confirm from popping up by default, but you can still listen for the message to come up. If you need to handle the confirmation differently, you'll need to use your own preload script.
Nightmare使得window.prompt默認不彈出,但你仍然可以聽到消息出現。
如果您需要以不同方式處理確認,則需要使用自己的預加載腳本。

.on('console', function(type [, arguments, ...]))

type will be either log, warn or error and arguments are what gets passed from the console. This event is not triggered if the injected javascript code (e.g. via .evaluate()) is using console.log.
類型將是日志,警告或錯誤,參數是從控制台傳遞的。如果注入的JavaScript代碼(例如,通過.evaluate())使用console.log,則不會觸發此事件。

.once(event, callback)

Similar to .on(), but captures page events with the callback one time.
與.on()類似,但一次捕獲具有回調的頁面事件。

.removeListener(event, callback)

Removes a given listener callback for an event.
刪除給定事件的偵聽器回調。

.screenshot([path][, clip])

Takes a screenshot of the current page. Useful for debugging. The output is always a png. Both arguments are optional. If path is provided, it saves the image to the disk. Otherwise it returns a Buffer of the image data. If clip is provided (as documented here), the image will be clipped to the rectangle.
截取當前頁面的屏幕截圖。用於調試。
輸出總是一個PNG。
兩個參數都是可選的。
如果提供路徑,它將圖像保存到磁盤。
否則它會返回圖像數據的緩沖區。
如果提供剪輯(如此處所述),圖像將被剪裁到矩形。

.html(path, saveType)

Saves the current page as html as files to disk at the given path. Save type options are here.
將當前頁面保存為html,並將文件保存到指定路徑的磁盤中。
保存類型選項在這里。

.pdf(path, options)

Saves a PDF to the specified path. Options are here.
將PDF保存到指定的路徑。
選項在這里。

.title()

Returns the title of the current page.
返回當前頁面的標題。

.url()

Returns the url of the current page.
返回當前頁面的網址。

.path()

Returns the path name of the current page.
返回當前頁面的路徑名稱。

Cookies

.cookies.get(name)

Gets a cookie by it's name. The url will be the current url.
通過它的名字獲取一個cookie。

.cookies.get(query)

Queries multiple cookies with the query object. If a query.name is set, it will return the first cookie it finds with that name, otherwise it will query for an array of cookies. If no query.url is set, it will use the current url. Here's an example:
用查詢對象查詢多個cookie。
如果設置了query.name,它將返回它找到的第一個cookie,否則它將查詢一個cookie數組。
如果沒有設置query.url,它將使用當前的url。
這是一個例子:

// get all google cookies that are secure
// and have the path `/query`
nightmare
  .goto('http://google.com')
  .cookies.get({
    path: '/query',
    secure: true
  })
  .then(cookies => {
    // do something with the cookies
  })

Available properties are documented here: https://github.com/atom/electron/blob/master/docs/api/session.md#sescookiesgetdetails-callback
這里記錄可用的屬性:

.cookies.get()

Gets all the cookies for the current url. If you'd like get all cookies for all urls, use: .get({ url: null }).
獲取當前網址的所有Cookie。如果您想為所有網址獲取所有Cookie,請使用:.get({url:null})。

.cookies.set(name, value)

Sets a cookie's name and value. This is the most basic form, and the url will be the current url.
設置cookie的名稱和值。這是最基本的形式,並且網址將成為當前網址。

.cookies.set(cookie)

Sets a cookie. If cookie.url is not set, it will set the cookie on the current url. Here's an example:
設置一個cookie。如果cookie.url未設置,它將在當前網址上設置cookie。這是一個例子:

nightmare
  .goto('http://google.com')
  .cookies.set({
    name: 'token',
    value: 'some token',
    path: '/query',
    secure: true
  })
  // ... other actions ...
  .then(() => {
    // ...
  })

Available properties are documented here: https://github.com/atom/electron/blob/master/docs/api/session.md#sescookiessetdetails-callback
這里記錄可用的屬性:

.cookies.set(cookies)

Sets multiple cookies at once. cookies is an array of cookie objects. Take a look at the .cookies.set(cookie) documentation above for a better idea of what cookie should look like.
一次設置多個Cookie。 cookie是一組cookie對象。查看上面的.cookies.set(cookie)文檔,以更好地了解cookie應該是什么樣子。

.cookies.clear([name])

Clears a cookie for the current domain. If name is not specified, all cookies for the current domain will be cleared.
清除當前域的Cookie。如果未指定名稱,則會清除當前域的所有Cookie。

nightmare
  .goto('http://google.com')
  .cookies.clear('SomeCookieName')
  // ... other actions ...
  .then(() => {
    // ...
  })

.cookies.clearAll()

Clears all cookies for all domains.
清除所有域的所有Cookie。

nightmare
  .goto('http://google.com')
  .cookies.clearAll()
  // ... other actions ...
  .then(() => {
    //...
  })

Proxies

Proxies are supported in Nightmare through switches.

If your proxy requires authentication you also need the authentication call.

The following example not only demonstrates how to use proxies, but you can run it to test if your proxy connection is working:
通過交換機在夢魘中支持代理。如果您的代理需要認證,您還需要認證呼叫。以下示例不僅演示了如何使用代理,但您可以運行它來測試代理連接是否正常工作:

import Nightmare from 'nightmare';

const proxyNightmare = Nightmare({
  switches: {
    'proxy-server': 'my_proxy_server.example.com:8080' // set the proxy server here ...
  },
  show: true
});

proxyNightmare
  .authentication('proxyUsername', 'proxyPassword') // ... and authenticate here before `goto`
  .goto('http://www.ipchicken.com')
  .evaluate(() => {
    return document.querySelector('b').innerText.replace(/[^\d\.]/g, '');
  })
  .end()
  .then((ip) => { // This will log the Proxy's IP
    console.log('proxy IP:', ip);
  });

// The rest is just normal Nightmare to get your local IP
const regularNightmare = Nightmare({ show: true });

regularNightmare
  .goto('http://www.ipchicken.com')
  .evaluate(() =>
    document.querySelector('b').innerText.replace(/[^\d\.]/g, '');
  )
  .end()
  .then((ip) => { // This will log the your local IP
    console.log('local IP:', ip);
  });

Promises ES6承諾

By default, Nightmare uses default native ES6 promises. You can plug in your favorite ES6-style promises library like bluebird or q for convenience!
默認情況下,Nightmare使用默認的本地ES6承諾。你可以插入你最喜歡的ES6風格的承諾庫,如藍鳥或Q為方便!

Here's an example:

var Nightmare = require('nightmare')

Nightmare.Promise = require('bluebird')
// OR:
Nightmare.Promise = require('q').Promise

You can also specify a custom Promise library per-instance with the Promise constructor option like so:
您還可以使用Promise構造函數選項為每個實例指定一個自定義Promise庫,如下所示:

var Nightmare = require('nightmare')

var es6Nightmare = Nightmare()
var bluebirdNightmare = Nightmare({
  Promise: require('bluebird')
})

var es6Promise = es6Nightmare
  .goto('https://github.com/segmentio/nightmare')
  .then()
var bluebirdPromise = bluebirdNightmare
  .goto('https://github.com/segmentio/nightmare')
  .then()

es6Promise.isFulfilled() // throws: `TypeError: es6EndPromise.isFulfilled is not a function`
bluebirdPromise.isFulfilled() // returns: `true | false`

Extending Nightmare

Nightmare.action(name, [electronAction|electronNamespace], action|namespace)

You can add your own custom actions to the Nightmare prototype. Here's an example:
您可以將自己的自定義操作添加到Nightmare原型中。這是一個例子:

Nightmare.action('size', function(done) {
  this.evaluate_now(() => {
    const w = Math.max(
      document.documentElement.clientWidth,
      window.innerWidth || 0
    )
    const h = Math.max(
      document.documentElement.clientHeight,
      window.innerHeight || 0
    )
    return {
      height: h,
      width: w
    }
  }, done)
})

Nightmare()
  .goto('http://cnn.com')
  .size()
  .then(size => {
    //... do something with the size information
  })

Remember, this is attached to the static class Nightmare, not the instance.

You'll notice we used an internal function evaluate_now. This function is different than nightmare.evaluate because it runs it immediately, whereas nightmare.evaluate is queued.

An easy way to remember: when in doubt, use evaluate. If you're creating custom actions, use evaluate_now. The technical reason is that since our action has already been queued and we're running it now, we shouldn't re-queue the evaluate function.

We can also create custom namespaces. We do this internally for nightmare.cookies.get and nightmare.cookies.set. These are useful if you have a bundle of actions you want to expose, but it will clutter up the main nightmare object. Here's an example of that:

請記住,這是附加到靜態類Nightmare,而不是實例。你會注意到我們使用了一個內部函數evaluate_now。此功能與nightmare.evaluate不同,因為它立即運行它,而nightmare.evaluate已排隊。一個簡單的方法來記住:如有疑問,請使用評估。如果您正在創建自定義操作,請使用evaluate_now。技術上的原因是,由於我們的操作已經排隊並且現在正在運行,所以我們不應該重新排列評估函數。我們也可以創建自定義名稱空間。我們在內部為nightmare.cookies.get和nightmare.cookies.set執行此操作。如果你有一堆你想要暴露的動作,這些是很有用的,但它會混淆主要的nightmare對象。這是一個例子:

Nightmare.action('style', {
  background(done) {
    this.evaluate_now(
      () => window.getComputedStyle(document.body, null).backgroundColor,
      done
    )
  }
})

Nightmare()
  .goto('http://google.com')
  .style.background()
  .then(background => {
    // ... do something interesting with background
  })

You can also add custom Electron actions. The additional Electron action or namespace actions take name, options, parent, win, renderer, and done. Note the Electron action comes first, mirroring how .evaluate() works. For example:
您還可以添加自定義Electron操作。額外的Electron動作或命名空間動作包括名稱,選項,父級,獲勝,渲染器和完成。請注意,Electron動作首先會反映.evaluate()如何工作。例如:

Nightmare.action(
  'clearCache',
  (name, options, parent, win, renderer, done) => {
    parent.respondTo('clearCache', done => {
      win.webContents.session.clearCache(done)
    })
    done()
  },
  function(done) {
    this.child.call('clearCache', done)
  }
)

Nightmare()
  .clearCache()
  .goto('http://example.org')
  //... more actions ...
  .then(() => {
    // ...
  })

...would clear the browser’s cache before navigating to example.org.

See this document for more details on creating custom actions.
...在導航到example.org之前會清除瀏覽器的緩存。有關創建自定義操作的更多細節,請參閱此文檔。

.use(plugin)

nightmare.use is useful for reusing a set of tasks on an instance. Check out nightmare-swiftly for some examples.
nightmare.use用於重用實例上的一組任務。快速查看一些例子的噩夢。

Custom preload script自定義預加載腳本

If you need to do something custom when you first load the window environment, you
can specify a custom preload script. Here's how you do that:
如果您在第一次加載窗口環境時需要自定義某些內容,則可以指定自定義預加載腳本。你如何做到這一點:

import path from 'path'

const nightmare = Nightmare({
  webPreferences: {
    preload: path.resolve('custom-script.js')
    //alternative: preload: "absolute/path/to/custom-script.js"
  }
})

The only requirement for that script is that you'll need the following prelude:
該腳本的唯一要求是您需要以下前奏:

window.__nightmare = {}
__nightmare.ipc = require('electron').ipcRenderer

To benefit of all of nightmare's feedback from the browser, you can instead copy the contents of nightmare's preload script.
為了從瀏覽器中獲得所有nightmare的反饋,您可以改為復制nightmare的預加載腳本的內容。

Storage Persistence between nightmare instances存儲持久性之間的噩夢實例

By default nightmare will create an in-memory partition for each instance. This means that any localStorage or cookies or any other form of persistent state will be destroyed when nightmare is ended. If you would like to persist state between instances you can use the webPreferences.partition api in electron.
默認情況下,nightmare會為每個實例創建一個內存分區。這意味着,當nightmare結束時,任何localStorage或cookie或任何其他形式的持久狀態都將被銷毀。如果你想在實例之間保持狀態,你可以在electron中使用webPreferences.partition api。

import Nightmare from 'nightmare';

nightmare = Nightmare(); // non persistent paritition by default
yield nightmare
  .evaluate(() => {
    window.localStorage.setItem('testing', 'This will not be persisted');
  })
  .end();

nightmare = Nightmare({
  webPreferences: {
    partition: 'persist: testing'
  }
});
yield nightmare
  .evaluate(() => {
    window.localStorage.setItem('testing', 'This is persisted for other instances with the same paritition name');
  })
  .end();

If you specify a null paritition then it will use the electron default behavior (persistent) or any string that starts with 'persist:' will persist under that partition name, any other string will result in in-memory only storage.
如果你指定一個空分區,那么它將使用electron默認行為(持久化),或者以'persist:'開頭的任何字符串將保留在該分區名稱下,任何其他字符串將導致僅存儲在內存中。

Usage

Installation

Nightmare is a Node.js module, so you'll need to have Node.js installed. Then you just need to npm install the module:
安裝Nightmare是一個Node.js模塊,所以你需要安裝Node.js。那么你只需要npm安裝模塊:

$ npm install --save nightmare

Execution

Nightmare is a node module that can be used in a Node.js script or module. Here's a simple script to open a web page:
執行Nightmare是一個節點模塊,可以在Node.js腳本或模塊中使用。這里有一個簡單的腳本來打開一個網頁:

import Nightmare from 'nightmare';

const nightmare = Nightmare();

nightmare.goto('http://cnn.com')
  .evaluate(() => {
    return document.title;
  })
  .end()
  .then((title) => {
    console.log(title);
  })

If you save this as cnn.js, you can run it on the command line like this:
如果你把它保存為cnn.js,你可以像這樣在命令行上運行它:

npm install --save nightmare
node cnn.js

Common Execution Problems

Nightmare heavily relies on Electron for heavy lifting. And Electron in turn relies on several UI-focused dependencies (eg. libgtk+) which are often missing from server distros.

For help running nightmare on your server distro check out How to run nightmare on Amazon Linux and CentOS guide.
常見執行問題Nightmare很大程度上依賴於Electron來舉重。而Electron依賴於幾個基於UI的依賴項(例如libgtk +),這些依賴項通常從服務器發行版中丟失。如需幫助在服務器上運行Nightmare發行版,請查看如何在Amazon Linux和CentOS指南上運行Nightmare。

Debugging

There are three good ways to get more information about what's happening inside the headless browser:

  1. Use the DEBUG=* flag described below.
  2. Pass { show: true } to the nightmare constructor to have it create a visible, rendered window where you can watch what is happening.
  3. Listen for specific events.

To run the same file with debugging output, run it like this DEBUG=nightmare node cnn.js (on Windows use set DEBUG=nightmare & node cnn.js).

This will print out some additional information about what's going on:
有三種好方法可以獲得關於無頭瀏覽器內發生的更多信息:使用下面描述的DEBUG = *標志。將{show:true}傳給夢魘構造函數,讓它創建一個可見的渲染窗口,在那里你可以看到發生了什么。傾聽特定事件。要使用調試輸出運行相同的文件,請像這樣運行DEBUG = nightmare節點cnn.js(在Windows上使用set DEBUG = nightmare&node cnn.js)。這將打印出一些關於正在發生的更多信息:

nightmare queueing action "goto" +0ms
nightmare queueing action "evaluate" +4ms
Breaking News, U.S., World, Weather, Entertainment & Video News - CNN.com
Debug Flags調試標志

All nightmare messages所有nightmare信息

DEBUG=nightmare*

Only actions只有行動

DEBUG=nightmare:actions*

Only logs只有日志

DEBUG=nightmare:log*

Additional Resources其他資源

羅斯欣克利的噩夢示例是設置惡夢,了解自定義操作以及避免常見陷阱的絕佳資源。Nightmare問題有許多獨立的可運行示例。腳本編號對應於噩夢問題編號。噩夢般的好消息是ÆndrewRininsland通過使用真實數據在夢魘中起床和運行的絕佳教程。

Tests

Automated tests for nightmare itself are run using Mocha and Chai, both of which will be installed via npm install. To run nightmare's tests, just run make test.

When the tests are done, you'll see something like this:
惡夢本身的自動測試使用Mocha和Chai進行,兩者都將通過npm install進行安裝。要運行惡夢的測試,只需運行make test。測試完成后,您會看到如下所示的內容:

make test
  ․․․․․․․․․․․․․․․․․․
  18 passing (1m)

Note that if you are using xvfb, make test will automatically run the tests under an xvfb-run wrapper. If you are planning to run the tests headlessly without running xvfb first, set the HEADLESS environment variable to 0.
請注意,如果您使用的是xvfb,則make test會自動運行xvfb運行包裝下的測試。如果您計划在無需首先運行xvfb的情況下無頭運行測試,請將HEADLESS環境變量設置為0。

License (MIT)

WWWWWW||WWWWWW
 W W W||W W W
      ||
    ( OO )__________
     /  |           \
    /o o|    MIT     \
    \___/||_||__||_|| *
         || ||  || ||
        _||_|| _||_||
       (__|__|(__|__|

Copyright (c) 2015 Segment.io, Inc. mailto:friends@segment.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM