昨天想写一个chrome爬虫插件,我用jq试了一下,情况是这样的:
var baseUrl = "http://www.example.com/";
function startFetch() {
$.get(baseUrl, function (data) {
var str = $('
$('#log').html(str);
});
}
$(function () {
$("#startFetch").bind("click", startFetch);
});
一开始发现,$.get返回的数据是一个完整的html代码,就像这样:
Document我直接用$(data)得到的是一个dom节点集合,而不是一个jq对象,stackoverflow上也有人问到这种情况,综合几种情况,我采用了$('
在用jq实现之后,我又用js重新写了一个,具体如下:
var baseUrl = "http://www.example.com/";
var get = request.bind(this, 'GET');
function startFetch() {
get(baseUrl, function (data) {
var newDiv, str;
newDiv = document.createElement('div');
newDiv.innerHTML = data; //这里如果改用appendChild就会报错
str = newDiv.querySelectorAll('selector')[1].innerHTML;
document.getElementById('log').innerHTML = str;
});
}
window.onload = function () {
document.getElementById('startFetch').addEventListener('click', startFetch);
};
function request(type, url, opts, callback) {
var xhr = new XMLHttpRequest();
if (typeof opts === 'function') {
callback = opts;
opts = null;
}
xhr.open(type, url);
var fd = new FormData();
if (type === 'POST' && opts) {
for (var key in opts) {
fd.append(key, JSON.stringify(opts[key]));
}
}
xhr.onload = function () {
callback(xhr.response);
};
xhr.send(opts ? fd : null);
}
以下是我完整的整个插件的结构:
|-js
|-popup.js
|-icon16.png
|-icon48.png
|-icon128.png
|-manifest.json
|-popup.html
完整代码如下:
//popup.html
Document#log {
width: 200px;
line-height: 20px;
}
获取账号密码
//manifest.json
{
"manifest_version": 2,
"name": "更新ss",
"description": "获取免费账号并更新到本地",
"version": "1.0",
"icons": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
},
"browser_action": {
"default_icon": "icon128.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"webRequest",
"webNavigation",
"webRequestBlocking",
"proxy",
"*://*/*"
]
}
popup.js的代码就是上面纯js版