【PUPPETEER】初探之執行JavaScript方法(六)

1、知識點

  1. page.evaluate()
  2. document.querySelector().value = '';

2、解析知識點

  page.evaluate(),查看puppeteer 的api , 經過api 咱們能夠大概瞭解,pgeFunction傳入的是一個頁面執行方法。返回一個pageFunction的執行結果。chrome

3、實例

1. 咱們今天作個案例,好比再同城上搜索某個時間段的機票,可是咱們發現,時間空間幾乎很難定位到,出發城市,到達城市能夠定位到而且能夠用page.type()方法輸入地址,可是時間呢,怎麼定位呢,咱們分析一下:api

1.時間元素,咱們能夠定位到把 :element = '#txtAirplaneTime1'less

2.再分析,咱們發現選中某個時間後,輸入框是「2019-08-20」async

3.那好了,咱們是否是直接運用js 把值傳進入就好了,也許有人問爲何page.type()不行,首先這個空間不是文本輸入,因此沒法使用type ui

4.打開控制檯調試下js代碼 document.querySelector("#txtAirplaneCity1").value = 「」  (自行調試,不演示了)lua

5.完整代碼spa

const puppeteer = require('puppeteer');
(async () => {
    const brower = await puppeteer.launch({
        executablePath:'D:\\wangxiao\\chrome-win\\chrome-win\\chrome.exe',
        headless:false,
        ignoreDefaultArgs:["--enable-automation"],
        defaultViewport:{width:1200,height:700}
    });
    const page = await brower.newPage();
    await page.goto('https://www.ly.com',{waitUntil:"networkidle2"});

    await page.waitFor("#txtAirplaneCity1");
    await page.waitFor("#txtAirplaneCity2");

    await page.evaluate(() => {
        document.querySelector("#txtAirplaneCity1").value = "上海";
        document.querySelector("#txtAirplaneCity2").value = "成都";
        document.querySelector("#txtAirplaneTime1").value = "2019-08-20";
    })

    const btn = await page.waitForSelector('#airplaneSubmit');
    await btn.click();

    
})().catch(error =>{console.log('error')});

相關文章
相關標籤/搜索