模塊導入示例
page.js
async function login(page, username, password) { await page.waitFor('input[id=userId]'); await page.type('input[id=userId]', username); await page.type('input[id=password]', password); await page.click('button[type="submit"]'); await page.waitFor('p.success-msg'); } module.exports = { login }
test.js
async function login(page, username, password) { await page.waitFor('input[id=userId]'); await page.type('input[id=userId]', username); await page.type('input[id=password]', password); await page.click('button[type="submit"]'); await page.waitFor('p.success-msg'); } module.exports = { login }
拖拽示例
const e = await page.$('#searchResultsSidebar'); const box = await e.boundingBox(); await page.mouse.move(box.x + box.width / 2, box.y + boy.height / 2); await page.mouse.down(); await page.mouse.move(100, 200); // move to (100, 200) coordinates await page.mouse.up();
xpath定位
const e = await page.$('#searchResultsSidebar'); const box = await e.boundingBox(); await page.mouse.move(box.x + box.width / 2, box.y + boy.height / 2); await page.mouse.down(); await page.mouse.move(100, 200); // move to (100, 200) coordinates await page.mouse.up();
獲取xpath表達式對應元素文本
const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com/'); const title = await page.$x("//h1"); let text = await page.evaluate(h1 => h1.textContent, title[0]); console.log(text) await browser.close();
雙擊
await page.click('.link-page-wrap',{ clickCount: 2 }); const foo = await page.$('.foo-item'); await = foo.click(); await = foo.click({ clickCount: 2 });
下載chromium
const browserFetcher = puppeteer.createBrowserFetcher(); const revisionInfo = await browserFetcher.download('533271'); const browser = await puppeteer.launch({executablePath: revisionInfo.executablePath})
顯示影藏的元素
await page.evaluate(() => { document.querySelector('mySelector').style.display = 'yes'; });
清空文本值
const puppeteer = require('puppeteer'); ;(async () => { const browser = await puppeteer.launch({headless: false}) const page = await browser.newPage() await page.goto('https://archive.kbb1.com/lessons', {waitUntil: 'networkidle2'}); // Clicking on Date filter // Click Apply and check if filter tag is created await Promise.all([ await page.click(".ui.blue.large.pointing.secondary.index-filters.menu div a:nth-child(4)"), page.waitForSelector("div.five.wide.column > div.ui.grid > div:nth-child(2) > div:nth-child(2) > div > input") ]); await page.$eval("div.five.wide.column > div.ui.grid > div:nth-child(2) > div:nth-child(1) > div > input[type=\"text\"]", (selector) => { selector.value = ""; }); await page.$eval(".class", (selector) => { selector.value = ""; }); })()
獲取某一個節點的某個屬性
const searchValue = await page.$eval('#search', el => el.value); const preloadHref = await page.$eval('link[rel=preload]', el => el.href); const text = await page.$eval('.text', el => el.textContent); const html = await page.$eval('.main-container', e => e.outerHTML);
獲取某一類節點的某個屬性集合
const textArray = await page.$$eval('.text', els => Array.from(els).map(el=> el.textContent));
beforall和afterall
beforeAll(async () => { browser = await puppeteer.launch({ headless: false, slowMo: 80 }); page = await browser.newPage(); }); afterAll(()=> { browser.close(); });
Jest 斷言
Matchers俗稱斷言庫,例如上面的expect().toBe()便是其中之一,其他常見用法如下:
1.相等斷言
toBe(value): 比較數字、字符串
toEqual(value): 比較對象、數組
toBeNull()
toBeUndefined()
2.包含斷言
toHaveProperty(keyPath, value): 是否有對應的屬性
toContain(item): 是否包含對應的值,括號里寫上數組、字符串
toMatch(regexpOrString): 括號里寫上正則
3.邏輯斷言
toBeTruthy()
toBeFalsy()
在JavaScript中,有六個falsy值:false,0,'',null, undefined,和NaN。其他一切都是Truthy。
toBeGreaterThan(number): 大於
toBeLessThan(number): 小於
4.not 取反,用法見下面例子
js去掉字符串的空格回車換行
例如下面這個json串,中間的\n表示換行
var str = "{' retmsg':'success ',\n' trans_date':' 20170906'}"; console.log(str); //"{' retmsg':'success ', //' trans_date':' 20170906'}"
去掉空格
str = str.replace(/\ +/g,""); console.log(str); //"{'retmsg':'success', //'trans_date':'20170906'}"
去掉回車換行
str = str.replace(/[\r\n]/g,""); console.log(str); //"{'retmsg':'success','trans_date':'20170906'}"