如何在PhantomJS中使用代理示例
var system = require('system');
var page = require('webpage').create();
// 请求地址 简单提取 具体需要根据实际情况获取 记得添加白名单 一般白名单添加后,10秒左右才生效
var api = ''; // 这里填写你购买后生成的API网址,如果没有或者不会,请找客服 如:http://www.soyunip.com/api?ddbh=s8349453653
function getProxyIp(callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', api, true);
xhr.timeout = 10000; // 超时设置为10秒
xhr.onload = function () {
if (xhr.status === 200) {
var ip = xhr.responseText.trim(); // 返回的内容如:125.26.21.154:13456
var ips = ip.split('\r\n'); // 这里返回多行多个代理IP,默认是以\r\n分隔符的
if (ips.length > 0 && ips[0]) {
callback(null, ips[0]); // 这里取第一个代理IP 实际应用时,根据需要自己选择
} else {
callback(new Error("No valid IP address found in response"));
}
} else {
callback(new Error("Failed to get IP address: HTTP error code : " + xhr.status));
}
};
xhr.onerror = function () {
callback(new Error("Network error"));
};
xhr.send();
}
getProxyIp(function (err, myip) {
if (err) {
console.error("An error occurred: " + err.message);
phantom.exit(1);
return;
}
// 代理服务器
var ipport = "http://" + myip;
// 设置代理
phantom.setProxy(ipport);
// 下面举例是你要访问的网站链接
var url = "http://myip.ipip.net";
page.open(url, function (status) {
if (status !== 'success') {
console.error("Failed to open the URL: " + status);
} else {
console.log(page.content); // 打印返回的内容
}
phantom.exit();
});
});