Hướng dẫn playwright python scraping - nhà viết kịch trăn cào

Như chúng ta đã biết, các headles browsers có khả năng thực thi mã JavaScript nhanh và mô phỏng việc nhấp hoặc di chuột vào các phần tử trên trang trên các thiết bị khác nhau. Các headles browsers cũng cực kỳ hữu ích khi kiểm tra hoạt động mạng, bắt chước các hành vi của người dùng khi sử dụng và tạo các requests. Chúng thường nhanh hơn các trình duyệt thực vì ta không cần khởi động GUI của trình duyệt, vậy nên ta có thể bỏ qua thời gian trình duyệt thực cần để tải CSS và JavaScript và hiển thị HTML. Bởi vậy, chúng thường được sử dụng trong quá trình kiểm thử tự đông nhằm đảm bảo mọi thứ hoạt động như dự định trước khi mã nguồn được triển khai lên môi trường production. Có nhiều giải pháp để viết các ca kiểm thử sử dụng headless browser và trong bài viết này, chúng ta sẽ cùng nhau tìm hiều về thư viện Playwright.

Nội dung chính

  • Playwright là gì?
  • Bắt đầu làm quen với Playwright
  • Viết các headless tests
  • Sử dụng Playwright với Mocha
  • Sử dụng với GitHub Action
  • Tổng kết
  • Tài liệu tham khảo

Nội dung chính

  • Playwright là gì?
  • Bắt đầu làm quen với Playwright
  • Viết các headless tests
  • Sử dụng Playwright với Mocha
  • Sử dụng với GitHub Action
  • Tổng kết
  • Tài liệu tham khảo

Playwright là gì?

Bắt đầu làm quen với Playwrightever-green, capable, reliable and fast.

Viết các headless tests

Hướng dẫn playwright python scraping - nhà viết kịch trăn cào

Sử dụng Playwright với Mocha
  • Sử dụng với GitHub Action
  • Tổng kết
  • Tài liệu tham khảo
  • Playwright is a Node.js library to automate Chromium, Firefox and WebKit with a single API. Playwright is built to enable cross-browser web automation that is ever-green, capable, reliable and fast.
  • Dựa vào phần giới thiệu Playwright, ta có thể hiểu qua rằng nó là một thư viện Node.js để tự động hóa Chromium, Firefox và WebKit bằng một API duy nhất. Thư viện Playwright được xây dựng để cho phép tự động hóa web trên nhiều trình duyệt, luôn được cập nhật các phiên bản mới nhất, ổn định, hiệu quả, đáng tin cậy và nhanh chóng. Playwright được viết bởi đội ngũ lập trình viên đến từ Microsoft, là dữ án mã nguồn mở, mã nguồn của nó được cung cấp trên Github tại https://github.com/microsoft/playwright
  • Playwright được xây dựng để tự động hóa hầu hết các tính năng trình duyệt web, những thứ ngày càng phổ biến rộng rãi được sử dụng bởi Single Page Apps và Progressive Web Apps. Với Playwright cung cấp cho chúng ta nhiều tiện ích như sau:
  • Thực hiện các kịch bản kiểm thử kéo dài bao gồm nhiều trang, tên miền và iframe

Bắt đầu làm quen với Playwright

Viết các headless tests

Sử dụng Playwright với Mocha

mkdir playright-example && cd playright-example && npm init -y

Sử dụng với GitHub Action

touch index.js && npm i --save playwright

Tổng kết

Viết các headless tests

Sử dụng Playwright với Mocha

Sử dụng với GitHub Action

Tổng kết

example-chromiumexample-firefox.pngexample-webkit.png

Sử dụng Playwright với Mocha

Sử dụng với GitHub Action

Bây giờ ta có thể tạo một kịch bản kiểm thử cơ bản kiểm thử trang web http://todomvc.com/examples/react/#/ Thông thường, ta sẽ tạo các tệp này trong một thư mục test, với tên tệp kết thúc bằng .spec.js:

const playwright = require('playwright')
const chai = require('chai')
const expect = chai.expect
const BASE_URL = 'http://todomvc.com/examples/react/#/'

let page, browser, context

describe('TO DO APP TESTS - PLAYWRIGHT', () => {

    beforeEach(async () => {
        browser = await playwright['chromium'].launch({ headless: false })
        context = await browser.newContext()
        page = await context.newPage(BASE_URL)
    })

    afterEach(async function() {
        await page.screenshot({ path: `${this.currentTest.title.replace(/\s+/g, '_')}.png` })
        await browser.close()
    })

    it('List is loaded empty', async() => {
        const sel = 'ul.todo-list li'
        const list = await page.$$(sel)
        expect(list.length).to.equal(0)
    })

    it('Adds a new todo in empty list', async() => {
        await page.waitForSelector('input')
        const element = await page.$('input')
        await element.type('Practice microsoft playwright')
        await element.press('Enter')

        // check list of ToDo
        const sel = 'ul.todo-list li'
        await page.waitForSelector(sel)
        const list = await page.$$(sel)
        expect(list.length).to.equal(1)
        expect(await page.$eval(sel, node => node.innerText)).to.be.equal('Practice microsoft playwright')
    })
})

Ví dụ này sẽ sử dụng Playwright để kết nối với trình duyệt Chrome. Nó sẽ mở http://todomvc.com/examples/react/#/ và thực hiện hai ca kiểm thử được định nghĩa ở trên. Để chạy thử chúng ta dùng lệnh sau:

 mocha # hoặc node_modules/mocha/bin/mocha

Kết quả thu được như hình sau, test case thứ có lỗi có thể do bị timeout. Mocha hỗ trợ chúng ta thay đổi giá trị mặc định bằng cách thêm

const {
  webkit,
  firefox,
  chromium
} = require('playwright');

const simulate = async (engine) => {

  const browser = await engine.launch();
  const page = await browser.newPage();

  await page.goto('http://whatsmyuseragent.org/');
  await page.screenshot({ path: `example-${engine._initializer.name}.png` });

  await browser.close();
};

simulate(firefox)
simulate(webkit)
simulate(chromium)
9 và giá trị thời gian khi gọi mocha để chạy test.

Sử dụng với GitHub Action

Chúng ta đều biết tự ra đời của Test automation và Continuous Integration/Continuous Development(CI-CD) là giải pháp được tạo ra để đảm bảo quá phát triển phần mềm hoạt động một cách liên tục, mượt mà trong khi vẫn đảm bảo chất lượng sản phẩm là một yêu cầu cấp thiết mà GitHub Action là một trong số đó. Để có thể sử dụng Playwright cùng với hệ thống này, chúng ta cần thực hiện một số bước như sau:

  • Thêm use:
    const playwright = require('playwright')
    const chai = require('chai')
    const expect = chai.expect
    const BASE_URL = 'http://todomvc.com/examples/react/#/'
    
    let page, browser, context
    
    describe('TO DO APP TESTS - PLAYWRIGHT', () => {
    
        beforeEach(async () => {
            browser = await playwright['chromium'].launch({ headless: false })
            context = await browser.newContext()
            page = await context.newPage(BASE_URL)
        })
    
        afterEach(async function() {
            await page.screenshot({ path: `${this.currentTest.title.replace(/\s+/g, '_')}.png` })
            await browser.close()
        })
    
        it('List is loaded empty', async() => {
            const sel = 'ul.todo-list li'
            const list = await page.$$(sel)
            expect(list.length).to.equal(0)
        })
    
        it('Adds a new todo in empty list', async() => {
            await page.waitForSelector('input')
            const element = await page.$('input')
            await element.type('Practice microsoft playwright')
            await element.press('Enter')
    
            // check list of ToDo
            const sel = 'ul.todo-list li'
            await page.waitForSelector(sel)
            const list = await page.$$(sel)
            expect(list.length).to.equal(1)
            expect(await page.$eval(sel, node => node.innerText)).to.be.equal('Practice microsoft playwright')
        })
    })
    
    1 vào định nghĩa GitHub workflow của GitHub trước khi chạy test.
on:
  push:
    branches:
    - master

jobs:
  e2e-tests:
    runs-on: ubuntu-latest # or macos-latest, windows-latest

    steps:
      - uses: actions/[email protected]

      - uses: actions/setup-[email protected]

      - uses: microsoft/playwright-github-[email protected]

      - name: Install dependencies and run tests
        run: npm install && npm test
  • Sau đó kết hợp action này với
    const playwright = require('playwright')
    const chai = require('chai')
    const expect = chai.expect
    const BASE_URL = 'http://todomvc.com/examples/react/#/'
    
    let page, browser, context
    
    describe('TO DO APP TESTS - PLAYWRIGHT', () => {
    
        beforeEach(async () => {
            browser = await playwright['chromium'].launch({ headless: false })
            context = await browser.newContext()
            page = await context.newPage(BASE_URL)
        })
    
        afterEach(async function() {
            await page.screenshot({ path: `${this.currentTest.title.replace(/\s+/g, '_')}.png` })
            await browser.close()
        })
    
        it('List is loaded empty', async() => {
            const sel = 'ul.todo-list li'
            const list = await page.$$(sel)
            expect(list.length).to.equal(0)
        })
    
        it('Adds a new todo in empty list', async() => {
            await page.waitForSelector('input')
            const element = await page.$('input')
            await element.type('Practice microsoft playwright')
            await element.press('Enter')
    
            // check list of ToDo
            const sel = 'ul.todo-list li'
            await page.waitForSelector(sel)
            const list = await page.$$(sel)
            expect(list.length).to.equal(1)
            expect(await page.$eval(sel, node => node.innerText)).to.be.equal('Practice microsoft playwright')
        })
    })
    
    2 để upload test artifacts (như screenshots hoặc logs).
steps:
- uses: microsoft/playwright-github-[email protected]

- name: Install dependencies and run tests
  run: npm install && npm test

- uses: actions/upload-[email protected]
  with:
    name: test-artifacts
    path: path/to/artifacts

Tổng kết

Mỗi công cụ trình duyệt đều có các quy tắc riêng để hiển thị HTML và CSS trên màn hình. Vậy nên các thư viện kiểm thử trên trình duyệt tự động có thể vô cùng hữu ích khi chúng ta muốn đảm bảo bố cục ứng dụng hoạt động đúng như những gì ta mong muốn trên tất cả các thiết bị và trình duyệt khác nhau mà

const playwright = require('playwright')
const chai = require('chai')
const expect = chai.expect
const BASE_URL = 'http://todomvc.com/examples/react/#/'

let page, browser, context

describe('TO DO APP TESTS - PLAYWRIGHT', () => {

    beforeEach(async () => {
        browser = await playwright['chromium'].launch({ headless: false })
        context = await browser.newContext()
        page = await context.newPage(BASE_URL)
    })

    afterEach(async function() {
        await page.screenshot({ path: `${this.currentTest.title.replace(/\s+/g, '_')}.png` })
        await browser.close()
    })

    it('List is loaded empty', async() => {
        const sel = 'ul.todo-list li'
        const list = await page.$$(sel)
        expect(list.length).to.equal(0)
    })

    it('Adds a new todo in empty list', async() => {
        await page.waitForSelector('input')
        const element = await page.$('input')
        await element.type('Practice microsoft playwright')
        await element.press('Enter')

        // check list of ToDo
        const sel = 'ul.todo-list li'
        await page.waitForSelector(sel)
        const list = await page.$$(sel)
        expect(list.length).to.equal(1)
        expect(await page.$eval(sel, node => node.innerText)).to.be.equal('Practice microsoft playwright')
    })
})
3 là một trong số đó.

Bài viết này giới thiệu sơ qua về thư viện

const playwright = require('playwright')
const chai = require('chai')
const expect = chai.expect
const BASE_URL = 'http://todomvc.com/examples/react/#/'

let page, browser, context

describe('TO DO APP TESTS - PLAYWRIGHT', () => {

    beforeEach(async () => {
        browser = await playwright['chromium'].launch({ headless: false })
        context = await browser.newContext()
        page = await context.newPage(BASE_URL)
    })

    afterEach(async function() {
        await page.screenshot({ path: `${this.currentTest.title.replace(/\s+/g, '_')}.png` })
        await browser.close()
    })

    it('List is loaded empty', async() => {
        const sel = 'ul.todo-list li'
        const list = await page.$$(sel)
        expect(list.length).to.equal(0)
    })

    it('Adds a new todo in empty list', async() => {
        await page.waitForSelector('input')
        const element = await page.$('input')
        await element.type('Practice microsoft playwright')
        await element.press('Enter')

        // check list of ToDo
        const sel = 'ul.todo-list li'
        await page.waitForSelector(sel)
        const list = await page.$$(sel)
        expect(list.length).to.equal(1)
        expect(await page.$eval(sel, node => node.innerText)).to.be.equal('Practice microsoft playwright')
    })
})
3 và cách thư viện này hoạt động, Để có thể tìm hiểu rõ hơn về thư viện này, cũng như tìm hiểu về điểm khác nhau giữa nó và
const playwright = require('playwright')
const chai = require('chai')
const expect = chai.expect
const BASE_URL = 'http://todomvc.com/examples/react/#/'

let page, browser, context

describe('TO DO APP TESTS - PLAYWRIGHT', () => {

    beforeEach(async () => {
        browser = await playwright['chromium'].launch({ headless: false })
        context = await browser.newContext()
        page = await context.newPage(BASE_URL)
    })

    afterEach(async function() {
        await page.screenshot({ path: `${this.currentTest.title.replace(/\s+/g, '_')}.png` })
        await browser.close()
    })

    it('List is loaded empty', async() => {
        const sel = 'ul.todo-list li'
        const list = await page.$$(sel)
        expect(list.length).to.equal(0)
    })

    it('Adds a new todo in empty list', async() => {
        await page.waitForSelector('input')
        const element = await page.$('input')
        await element.type('Practice microsoft playwright')
        await element.press('Enter')

        // check list of ToDo
        const sel = 'ul.todo-list li'
        await page.waitForSelector(sel)
        const list = await page.$$(sel)
        expect(list.length).to.equal(1)
        expect(await page.$eval(sel, node => node.innerText)).to.be.equal('Practice microsoft playwright')
    })
})
5 cũng như cách nó hoạt động với các hệ thống CI/CD, mọi người có thể đọc thêm tại đường dẫn bên dưới. Bài viết đến đây là hết, cảm ơn mọi người đã giành thời gian đọc.

Tài liệu tham khảo

  • https://github.com/microsoft/playwright
  • https://testguild.com/what-is-playwright/