为了解决无法使用随机选择器点击Facebook div的问题,我想使用移动版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");
页面重定向至桌面版本。然后我将用户代理更改为移动用户代理:
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;]",
);
然后返回此错误:
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
来自 UserAgents.io 的其他几个用户代理也不能正常工作。我可以使用
mbasic.facebook.com
来解决这个问题,但为了学习,我想知道为什么代码不起作用。
您可以使用Page.emulate加载移动版本。唯一的问题是您必须在加载页面之前模拟或设置用户代理,而不是之后。
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();
输出示例: