Skip to content

Instantly share code, notes, and snippets.

@anish000kumar
Last active June 4, 2024 18:34
Show Gist options
  • Save anish000kumar/0146d77b80b806ed168b1b278b2bb58e to your computer and use it in GitHub Desktop.
Save anish000kumar/0146d77b80b806ed168b1b278b2bb58e to your computer and use it in GitHub Desktop.
puppo
import puppeteer, { Browser, ElementHandle, Page } from "puppeteer";
export async function getPageHandler(url, openPage, delayMillis, headless = false) {
const openBrowser = await puppeteer.launch({
headless,
});
let page;
if(!openPage){
page = await openBrowser.newPage();
} else {
page = openPage
}
await page.goto(url);
async function _click(selector) {
await click(page, selector)
await delay(delayMillis)
}
async function _fillControl(selector, value, backspacePressCount = 0) {
await fillControl(page, selector, value, backspacePressCount)
await delay(delayMillis)
}
async function getText(selector) {
const el = await page.$(selector)
if (el) {
return el.evaluate(el => el?.textContent)
}
return ""
}
async function safeClick(selector) {
const el = await page.$(selector)
if (el) {
el.evaluate(el => el?.click())
}
}
return {
page,
click: _click,
getText,
safeClick,
fillControl: _fillControl
}
}
export async function fillControl(page, selector, value, backspacePressCount= 10) {
const input = await page.waitForSelector(selector)
const type = await (await input.getProperty("type")).jsonValue()
// Type the value into the input element
switch (type) {
case "select":
// Select an option from a dropdown
await input.select(value)
break
case "checkbox":
// Check or uncheck a checkbox
if (value.toLowerCase() === "true") {
await input?.click()
} else {
await input?.click()
}
break
case "radio":
// Select a radio button
const radioButton = await page.waitForSelector(
`input[type="radio"]${selector}[value="${value}"]`
)
await radioButton?.click()
break
case "number":
// Type a number into a number input
await input.type(value)
break
case "date":
case "time":
case "datetime-local":
// Type a date/time into a date input
await input.type(value)
break
case "textarea":
// Type into a textarea input
if(backspacePressCount > 0){
input.type(" ")
for(let i = 0; i < backspacePressCount+1; i++){
await page.keyboard.press('ArrowRight')
await page.keyboard.press('Backspace')
}
}
await input.type(value)
break
// Handle other input types
default:
if(backspacePressCount > 0){
input?.type(" ")
for(let i = 0; i < backspacePressCount+1; i++){
await page.keyboard.press('ArrowRight')
await page.keyboard.press('Backspace')
}
}
await input?.type(value)
break
}
}
export function delay(time) {
return new Promise(resolve => setTimeout(resolve, time))
}
export async function click(page, selector) {
const button = await page.waitForSelector(selector)
await button?.click()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment