愉快滴抓取链家地图找房中的商圈
[ 2020/08/28, JavaScript , 2680阅, 0评 ]

首先,将自定义的监听xhr事件的方法override原本的XMLHttpRequest(from:分享JavaScript监听全部Ajax请求事件的方法

(function () {
	if (typeof window.CustomEvent === "function") return false;
	function CustomEvent(event, params) {
		params = params || {
			bubbles: false,
			cancelable: false,
			detail: undefined
		};
		var evt = document.createEvent('CustomEvent');
		evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
		return evt;
	}
	CustomEvent.prototype = window.Event.prototype;
	window.CustomEvent = CustomEvent;
})();
(function () {
	function ajaxEventTrigger(event) {
		var ajaxEvent = new CustomEvent(event, {
			detail: this
		});
		window.dispatchEvent(ajaxEvent);
	}
	var oldXHR = window.XMLHttpRequest;
	function newXHR() {
		var realXHR = new oldXHR();
		realXHR.addEventListener('abort', function () {
			ajaxEventTrigger.call(this, 'ajaxAbort');
		}, false);
		realXHR.addEventListener('error', function () {
			ajaxEventTrigger.call(this, 'ajaxError');
		}, false);
		realXHR.addEventListener('load', function () {
			ajaxEventTrigger.call(this, 'ajaxLoad');
		}, false);
		realXHR.addEventListener('loadstart', function () {
			ajaxEventTrigger.call(this, 'ajaxLoadStart');
		}, false);
		realXHR.addEventListener('progress', function () {
			ajaxEventTrigger.call(this, 'ajaxProgress');
		}, false);
		realXHR.addEventListener('timeout', function () {
			ajaxEventTrigger.call(this, 'ajaxTimeout');
		}, false);
		realXHR.addEventListener('loadend', function () {
			ajaxEventTrigger.call(this, 'ajaxLoadEnd');
		}, false);
		realXHR.addEventListener('readystatechange', function () {
			ajaxEventTrigger.call(this, 'ajaxReadyStateChange');
		}, false);
		return realXHR;
	}
	window.XMLHttpRequest = newXHR;
})();

然后使用上面自定义的方法进行监听,筛选出所需要的接口并拿到返回的数据,再发送数据到自己的接口进行存储等操作。

window.addEventListener('ajaxLoadEnd', function (e) {
	let { response, responseURL } = e.detail
	if (responseURL.includes('save_lianjia_sq')) {
		console.log(response)
	}
	if(!/.*map\/bubblelist.*groupType\=bizcircle.*/.test(responseURL)) return;
	let cityCode = responseURL.match(/(?<=cityId\=)\d{6}/g)[0]
	let resInfo = JSON.parse(response)
	var xhrMy = new XMLHttpRequest()
	xhrMy.open("post", "http://127.0.0.1:8889/transfer/spider/save_lianjia_sq")
	xhrMy.setRequestHeader("Content-type", "application/json")
	xhrMy.send(JSON.stringify({
		activeCity: cityCode,
		activeSq: resInfo.data.bubbleList
	}))
});

最终使用方法:打开链家地图找房,f12然后输入上方所有js代码,将地图缩放到显示商圈的那一级,拖动到相应区域,该区域的商圈信息就会被发送到指定的接口了。

PS:通过这种在控制台注入js的方法还可以实现一些其他有趣的功能。

有朋自远方来...评论一下呗O(∩_∩)O