Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.0k views
in Technique[技术] by (71.8m points)

javascript - Click on object and get attributes with Puppeteer TS: evaluateOnNewDocument not working

I am creating an automated scraper which get the selector when you click on an element during navigation. I made this code in JavaScript and It works fine

async function main (initialUrl){
  
  let browser = await puppeteer.launch({ headless: false });
  let page = await browser.newPage();

  // Execute when a click is made on the window
  await page.exposeFunction('onClick',onClick );
  
  // Listening for click events on the window
  await page.evaluateOnNewDocument(() => {
    window.addEventListener('click', (event) => {
      let tagName = event.target.tagName
      let eClass = event.target.getAttribute("class")
      let id = event.target.getAttribute("id")
      window.onClick(tagName, eClass, id);
    });
  });
  await page.goto(initialUrl);
  }

function onClick (tagName, eClass, id){
  console.log(`You have clicked on: id: #${id} class: .${eClass} tagName: ${tagName}`);
  let selector =  getSelector(tagName, eClass, id);
  console.log('selector: ', selector)
  elementClicked(selector,page)
}

However, I am trying to migrate this code to TypeScript and the function page.evaluateOnNewDocument does not run.

async function main (initialUrl:string){
  
  let browser = await puppeteer.launch({ headless: false });
  let page = await browser.newPage();

  // Execute when a click is made on the window
  await page.exposeFunction('onClick',onClick);
  
  // Listening for click events on the window
  await page.evaluateOnNewDocument(() => {
    console.log('I am at evaluate') //does not show
    window.addEventListener('click', (event:MouseEvent) => {
      console.log('I am clicking') //does not show
      // let tagName:string = (event.target as HTMLElement).tagName;
      // let eClass:string = (event.target as HTMLElement).getAttribute("class")!;
      // let id:string = (event.target as HTMLElement).getAttribute("id")!;
      // window.onClick(tagName, eClass, id,page);
    });
  });
  await page.goto(initialUrl);
  }

function onClick(tagName:string, eClass:string, id:string,page:any){
  console.log(`You have clicked on: id: #${id} class: .${eClass} tagName: ${tagName}`);
  let selector =  getSelector(tagName, eClass, id);
  console.log('selector: ', selector)
  elementClicked(selector,page)
}

Any ideas why this is not working?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...