Skip to content

Instantly share code, notes, and snippets.

@keegoo
Created November 7, 2019 03:24
Show Gist options
  • Save keegoo/dee7875e5e7d029b5f4071f8ef2b114b to your computer and use it in GitHub Desktop.
Save keegoo/dee7875e5e7d029b5f4071f8ef2b114b to your computer and use it in GitHub Desktop.
const puppeteer = require('puppeteer')
class Element {
constructor(parent, css='body') {
this._parent = parent
this._css = css
this._page = this._parent.constructor.name == 'Page' ? this._parent : this._parent._page
}
async goto(url) {
return await this._page.goto(url)
}
async click() {
return await (await this.find_element()).click()
}
async type(text) {
return await (await this.find_element()).type(text)
}
async find_element() {
const _context = this._page
if (this._parent.constructor.name == 'Element')
_context = await this._parent.find_element()
await this._page.waitForSelector(this._css)
return await _context.$(this._css)
}
}
class Google extends Element {
constructor(parent, css) {
super(parent, css)
this.search_field = new Element(this, 'input.gsfi')
this.search_button = new Element(this, 'input[name="btnK"]')
this.result = new Element(this, '.g .r > a')
}
async search(text) {
await this.search_field.type(text)
await this.search_button.click()
}
}
async function main() {
const browser = await puppeteer.launch({headless: false})
google = new Google(await browser.newPage())
await google.goto('https://www.google.com/')
await google.search('hello')
await browser.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment