Created
April 13, 2024 14:22
-
-
Save nicolasmelo1/4f4aa46bacb41eb60d46e2a9db4acdb7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import puppeteer, { Page } from "puppeteer"; | |
const INSTAGRAM_HOST = "https://www.instagram.com/"; | |
export default async function instagram( | |
username: string, | |
password: string, | |
options?: { headless: boolean } | |
) { | |
const [page, browser] = await initialize(); | |
await login(page); | |
/** | |
* Initialize the puppeteer browser instance and keep it running until we finish what needs to be done | |
*/ | |
async function initialize() { | |
const browser = await puppeteer.launch({ | |
headless: false, | |
defaultViewport: { width: 900, height: 900 }, | |
}); | |
const openedPages = await browser.pages(); | |
const page = openedPages[0]; | |
await page.goto(INSTAGRAM_HOST); | |
await page.waitForNetworkIdle(); | |
return [page, browser] as const; | |
} | |
/** | |
* Logs the user into Instagram so we can start interacting with the page. | |
*/ | |
async function login(page: Page) { | |
await page.type("input[name=username]", username); | |
await page.type("input[name=password]", password); | |
await page.click("button[type=submit]"); | |
await page.waitForNetworkIdle(); | |
const handles = await page.$$("a"); | |
await handles[0].click(); | |
await page.waitForNetworkIdle(); | |
const buttons = await page.$$("button"); | |
for (const button of buttons) { | |
const value = await page.evaluate((button) => button.textContent, button); | |
if (value === "Not Now") { | |
await button.click(); | |
break; | |
} | |
} | |
} | |
async function followTheUsersBack() { | |
const page = await browser.newPage(); | |
await page.goto(INSTAGRAM_HOST + username + "/followers/"); | |
await page.waitForNetworkIdle(); | |
const buttons = await page.$$("button"); | |
for (const button of buttons) { | |
const valueOfPreviousSibling = await page.evaluate( | |
(button) => button?.previousSibling?.textContent || "", | |
button | |
); | |
if (valueOfPreviousSibling === "·") await button.click(); | |
} | |
// TODO: Probably there is scroll and pagination, need to check on that. | |
page.close(); | |
} | |
async function extractStories() { | |
} | |
async function close() { | |
await browser.close(); | |
} | |
return { | |
close, | |
followTheUsersBack, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment