Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer: Get innerHTML

Does anybody know how to get the innerHTML or text of an element? Or even better; how to click an element with a specific innerHTML? This is how it would work with normal JavaScript:

var found = false $(selector).each(function() {     if (found) return;     else if ($(this).text().replace(/[^0-9]/g, '') === '5' {         $(this).trigger('click');         found = true     } }); 

Thanks in advance for any help!

like image 324
Noah Avatar asked Sep 26 '17 16:09

Noah


People also ask

How do I get an element from innerHTML?

How it works. First, get the <ul> element with the id menu using the getElementById() method. Second, create a new <li> element and add it to the <ul> element using the createElement() and appendChild() methods. Third, get the HTML of the <ul> element using the innerHTML property of the <ul> element.


2 Answers

This is how i get innerHTML:

page.$eval(selector, (element) => {   return element.innerHTML }) 
like image 79
Ryan Avatar answered Sep 21 '22 20:09

Ryan


Returning innerHTML of an Element

You can use the following methods to return the innerHTML of an element:

page.$eval()

const inner_html = await page.$eval('#example', element => element.innerHTML); 

page.evaluate()

const inner_html = await page.evaluate(() => document.querySelector('#example').innerHTML); 

page.$() / elementHandle.getProperty() / jsHandle.jsonValue()

const element = await page.$('#example'); const element_property = await element.getProperty('innerHTML'); const inner_html = await element_property.jsonValue(); 

Clicking an Element with Specific innerHTML

You can use the following methods to click on an element based on the innerHTML that is contained within the element:

page.$$eval()

await page.$$eval('.example', elements => {   const element = elements.find(element => element.innerHTML === '<h1>Hello, world!</h1>');   element.click(); }); 

page.evaluate()

await page.evaluate(() => {   const elements = [...document.querySelectorAll('.example')];   const element = elements.find(element => element.innerHTML === '<h1>Hello, world!</h1>');   element.click(); }); 

page.evaluateHandle() / elementHandle.click()

const element = await page.evaluateHandle(() => {   const elements = [...document.querySelectorAll('.example')];   const element = elements.find(element => element.innerHTML === '<h1>Hello, world!</h1>');   return element; });  await element.click(); 
like image 27
Grant Miller Avatar answered Sep 22 '22 20:09

Grant Miller