To deal with the problem of not being able to click a Facebook div with randomized selector, I want to use the mobile version of Facebook (m.facebook.com
):
import puppeteer from "npm:puppeteer";
const browser = await puppeteer.launch({
executablePath: "C:/Users/ganuo/.cache/puppeteer/chrome/win64-125.0.6422.60/chrome-win64/chrome.exe",
headless: false,
userDataDir: "./user_data",
});
const page = await browser.newPage();
await page.goto("https://m.facebook.com/qua.cau.the.sphere");
The page redirects to the desktop version. I then change the user agent to the mobile one:
await page.setUserAgent(
"Mozilla/5.0 (Linux; Android 12; M2003J15SC Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/130.0.6723.99 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/489.0.0.66.81;IABMV/1;]",
);
then it returns this error:
error: Uncaught (in promise) Error: net::ERR_ABORTED at https://m.facebook.com/qua.cau.the.sphere
at navigate (file:///C:/Users/ganuo/AppData/Local/deno/npm/registry.npmjs.org/puppeteer-core/23.6.1/lib/esm/puppeteer/cdp/Frame.js:181:27)
at eventLoopTick (ext:core/01_core.js:214:9)
at async Function.race (file:///C:/Users/ganuo/AppData/Local/deno/npm/registry.npmjs.org/puppeteer-core/23.6.1/lib/esm/puppeteer/util/Deferred.js:33:20)
at async CdpFrame.goto (file:///C:/Users/ganuo/AppData/Local/deno/npm/registry.npmjs.org/puppeteer-core/23.6.1/lib/esm/puppeteer/cdp/Frame.js:147:25)
at async CdpPage.goto (file:///C:/Users/ganuo/AppData/Local/deno/npm/registry.npmjs.org/puppeteer-core/23.6.1/lib/esm/puppeteer/api/Page.js:570:20)
at async file:///D:/QC supplements/Code/Apps/Xây nhân hiệu tự động/puppeteer.js:15:1
A couple other user-agents from UserAgents.io don't work as well. I can workaround this by using mbasic.facebook.com
, but for the sake of learning I wonder why the code doesn't work.
You can use the Page.emulate to load the mobile version. The only catch is you have to emulate or set user agent before loading the page, not after.
import puppeteer, { KnownDevices } from 'puppeteer';
const iPhone = KnownDevices['iPhone 15 Pro'];
async function run() {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.emulate(iPhone);
await page.goto("https://m.facebook.com/qua.cau.the.sphere");
}
run();
Example output: