嘿,我一直在尝试将socks5代理连接到puppeteer,但它给我抛出了这个错误“不支持代理”..抱歉我使用电话来提问,
我本来会发送屏幕截图和代码...但是我从 proxy.json 获取代理并在我的 action.js 代码中使用它们,这就是它向我抛出错误的时候..任何人都知道我怎么能有机会任何我如何使用或管理使用带有 puppeteer Nodejs 的袜子5代理以及任何示例简单代码的示例
const fs = require('fs');
const path = require('path');
const { Person } = require("../../../HUMAN MODEL/personality.js");
// Ensure this path is correct
//const Behavior = require("../../BEHAVIOR MODEL/actions.js"); //
Ensure this path is correct
//const behavior = require("../../BEHAVIOR MODEL/yt_direct.js");
const Behavior = require("../../../BEHAVIOR MODEL/yt_search.js");
// Load proxy settings from proxy.json
const proxyPath = 'E:\\WORK PLACE\\Traffic
Bot\\Devices\\Iphones\\iphone 15 pro max\\proxy.json';
let proxySettings;
try {
const proxyData = fs.readFileSync(proxyPath, 'utf-8');
proxySettings = JSON.parse(proxyData);
// Log the loaded proxy settings
console.log('Proxy settings loaded:', proxySettings);
// Validate required proxy fields
if (!proxySettings.proxyServer || !proxySettings.proxyUsername || !proxySettings.proxyPassword || !proxySettings.timezone) {
throw new Error("Proxy settings missing required fields.");
}
} catch (error) {
console.error('Error reading or validating proxy settings:',
error.message);
process.exit(1);
}
const modeled = {
"Account": {
"fullname": "maarin",
"email": "[email protected]", // Add your email here
"password": "your_password" // Add your password here
},
"cookie": [],
"LocalStorage": [],
"cookieType": "Youtube",
"Device": {
"resolution": {
"width": 430,
"height": 932
},
"userAgent": "Mozilla/7.0 (iPhone; CPU iPhone OS 18_7; iPhone 15 Pro Max) AppleWebKit/533.2 (KHTML, like Gecko) CriOS/432.0.8702.51 Mobile/15E148 Safari/804.17",
"isMobile": true,
"hasTouch": true,
//"timezone": proxySettings.timezone,
"deviceName": "Apple iPhone 15 Pro Max"
},
"Location": {
"proxyType": proxySettings.proxyType,
"proxyServer": proxySettings.proxyServer,
"proxyUsername": proxySettings.proxyUsername,
"proxyPassword": proxySettings.proxyPassword,
},
"memo": {
"about": "I am a Female from Nigeria",
"device": "I am currently using the Apple iPhone 15 Pro Max"
}
};
async function runBot() {
try {
const teebot = new Person('maarin_cookies.json');
// Configure the bot
teebot.modelAccount(modeled.Account);
teebot.modelDevice(modeled.Device);
teebot.modelLocation(modeled.Location);
teebot.modelcookie(modeled.cookie);
teebot.showBrowser(true); // Set headless to true/false as needed
console.log("Starting bot life...");
let teebotBrowserPage = await teebot.startLife(modeled);
console.log("Bot started successfully.");
// Log in to Google
await teebot.loginToGoogle();
// Instantiate the Behavior class and perform actions
const actions = new Behavior(teebotBrowserPage);
await actions.directVisit();
// Set a valid URL to visit
const urlToVisit = "https://whatismyipaddress.com/";
console.log("URL to visit:", urlToVisit);
await actions.directVisit(urlToVisit);
// Export human model data
await teebot.exportHuman(modeled);
// Close the browser
await teebot.close();
} catch (error) {
console.error('Error during bot execution:', error.message);
}
}
runBot();
上面的代码是运行机器人的代码,下面的代码是我的个性js:
const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
// Ensure the directory for cookies exists
async function ensureDirectory(dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
// Function to wait for a specified amount of time
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Function to type text in a human-like manner
async function humanLikeTyping(page, selector, text) {
await page.focus(selector);
for (const char of text) {
await page.keyboard.type(char);
await sleep(Math.random() * 200 + 100); // Random delay between
100ms and 300ms
}
}
class Person {
constructor(cookiesFileName) {
this.browser = null;
this.page = null;
this.account = {};
this.device = {};
this.location = {};
this.cookiesFileName = cookiesFileName || 'cookies.json';
this.cookiesDir = path.join(__dirname, 'cookies');
this.headless = false; // Default to headless mode
}
async startLife(modeled = {}) {
await ensureDirectory(this.cookiesDir); // Ensure directory
exists
// Debugging log for the modeled object
console.log("Modeled object received in startLife:",
JSON.stringify(modeled, null, 2));
if (!modeled.Location || !modeled.Location.proxyUsername ||
!modeled.Location.proxyPassword || !modeled.Location.proxyServer)
{
console.error("Missing proxy configuration in the modeled
object:", JSON.stringify(modeled.Location, null, 2));
throw new Error('Missing proxy configuration in the modeled
object.');
}
console.log("Proxy configuration exists. Proceeding with
Puppeteer launch...");
const proxyUrl =`socks5://${modeled.Location.proxyUsername}:${modeled.Location.proxyPassword}@${modeled.Location.proxyServer}`;
this.browser = await puppeteer.launch({
headless: this.headless,
timeout: 60000, // Increase timeout to 60 seconds
args: [
'--proxy-server=socks5://localhost:1081',
'--proxy-server=socks5://‘proxy-host’:‘proxy-port’',
`--proxy-server=${proxyUrl}`, // Use the proxy URL
`--window-size=${this.device.resolution.width || 1200},${this.device.resolution.height || 800}`,
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-blink-features=AutomationControlled',
'--disable-dev-shm-usage',
'--disable-extensions',
'--disable-default-apps',
'--disable-gpu',
'--no-first-run',
'--no-zygote',
'--single-process',
'--hide-scrollbars',
'--disable-infobars',
'--disable-features=IsolateOrigins,site-per-process',
'--disable-web-security',
'--disable-features=BlockInsecurePrivateNetworkRequests'
]
});
console.log("Puppeteer launched successfully.");
this.page = await this.browser.newPage();
await this.page.setBypassCSP(true);
await this.page.setViewport({
width: this.device.resolution?.width || 1200,
height: this.device.resolution?.height || 800,
isMobile: this.device.isMobile || false,
hasTouch: this.device.hasTouch || false,
});
if (this.device.userAgent) {
console.log("Setting user agent:", this.device.userAgent);
await this.page.setUserAgent(this.device.userAgent);
}
// Set timezone
if (this.device.timezone) {
console.log("Emulating timezone:", this.device.timezone);
await this.page.emulateTimezone(this.device.timezone);
}
// Load cookies if they exist
console.log("Loading cookies...");
await this.loadCookies();
console.log("Cookies loaded.");
return this.page;
}
async loginToGoogle() {
try {
console.log('Entering email...');
await humanLikeTyping(this.page, 'input[type="email"]', this.account.email);
await this.page.click('#identifierNext');
await sleep(3000);
console.log('Entering password...');
await this.page.waitForSelector('input[type="password"]', { visible: true });
await humanLikeTyping(this.page, 'input[type="password"]', this.account.password);
await this.page.click('#passwordNext');
await this.page.waitForNavigation({ waitUntil: 'networkidle2' });
console.log(`${this.account.email} logged in successfully.`);
await this.saveCookies();
} catch (error) {
console.error('Error logging in:', error);
}
}
modelAccount(account) {
console.log("Modeling account:", account);
this.account = account;
}
modelDevice(device) {
console.log("Modeling device:", device);
this.device = device;
}
modelLocation(location) {
console.log("Modeling location with proxy settings:", location);
this.location = location;
if (location.proxyServer) {
const proxyUrl = `socks5://${location.proxyUsername}:${location.proxyPassword}@${location.proxyServer}`;
process.env.HTTP_PROXY = proxyUrl;
process.env.HTTPS_PROXY = proxyUrl;
}
}
modelcookie(cookies) {
console.log("Modeling cookies:", cookies);
this.cookies = cookies;
}
showBrowser(show) {
console.log(`Setting headless mode to: ${!show}`);
this.headless = !show;
}
async exportHuman(modeled) {
fs.writeFileSync('humanModel.json', JSON.stringify(modeled, null, 2));
console.log("Human model exported.");
}
async saveCookies() {
try {
if (this.page) {
const cookies = await this.page.cookies();
const cookiesPath = path.join(this.cookiesDir, this.cookiesFileName);
fs.writeFileSync(cookiesPath, JSON.stringify(cookies, null, 2));
console.log(`Cookies saved to ${cookiesPath}.`);
} else {
console.error('Cannot save cookies, page is closed.');
}
} catch (error) {
console.error('Error saving cookies:', error);
}
}
async loadCookies() {
try {
const cookiesPath = path.join(this.cookiesDir, this.cookiesFileName);
if (fs.existsSync(cookiesPath)) {
const cookies = JSON.parse(fs.readFileSync(cookiesPath));
await this.page.setCookie(...cookies);
console.log(`Cookies loaded from ${cookiesPath}.`);
} else {
console.log('No cookies file found.');
}
} catch (error) {
console.error('Error loading cookies:', error);
}
}
async close() {
try {
await this.saveCookies();
if (this.browser) {
await this.browser.close();
}
} catch (error) {
console.error('Error closing browser:', error);
}
}
}
module.exports = { Person };
现在这是我的 proxyjson 文件:
{
"proxyType": "socks5",
"proxyServer": "socks5://8888:8",
"proxyUsername": "my username",
"proxyPassword": "my pass word",
"timezone": "America/Los_Angeles"
}
根据 Chrome 文档中的 代理支持,您只需使用
--proxy-server="socks5://host:port"
将 host
和 port
替换为您的代理信息。
但是,Chrome 不支持通过
--proxy-server
传递凭据,因此需要身份验证的代理必须通过凭据解析流程进行授权。请参阅文档中的以下片段:
Chrome 没有实现这一点,并且不会使用代理设置中嵌入的任何凭据。
代理身份验证将通过普通流程来查找凭据。