我想模拟搜索当前标签页面的一个查询参数,并返回结果网页的内容。我该怎么做?
例如,如果用户在http://www.quora.com/JavaScript/Why-is-function-an-object-in-Javascript
我想模拟用户在Quora上搜索“JavaScript”,并获取生成的网页http://www.quora.com/JavaScript
的内容(包括由ajax填充的数据)。
我可以在服务器上使用casper.js,但这会增加延迟。我更喜欢在客户端上模拟这个。
答案 0 :(得分:1)
你去http://www.google.com/cse/然后创建一个自定义搜索引擎 你有2个代码: 表单搜索:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
google.setOnLoadCallback(function() {
google.search.CustomSearchControl.attachAutoCompletion(
'006309227296184785814:f9bcc86z5hm',
document.getElementById('q'),
'cse-search-box');
});
</script>
<form action="" id="cse-search-box">
<div>
<input type="hidden" name="cx" value="006309227296184785814:f9bcc86z5hm" />
<input type="hidden" name="cof" value="FORID:10" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" id="q" autocomplete="off" size="30" onKeyPress="return SubmitOnEnter(this,event)" />
<input type="submit" class="tim" name="sa" value="Search" onclick="SearchSite();" />
</div>
</form>
<script type="text/javascript" src="http://www.google.com/cse/brand?form=cse-search-box&lang=en"></script>
Create function for search:
function URLEncode (clearString) {
var output = '';
var x = 0;
clearString = clearString.toString();
var regex = /(^[a-zA-Z0-9_.]*)/;
while (x < clearString.length) {
var match = regex.exec(clearString.substr(x));
if (match != null && match.length > 1 && match[1] != '') {
output += match[1];
x += match[1].length;
} else {
if (clearString[x] == ' ')
output += '+';
else {
var charCode = clearString.charCodeAt(x);
var hexVal = charCode.toString(16);
output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
}
x++;
}
}
return output;
}
function SubmitOnEnter(myfield, e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
else
return true;
if (keycode == 13)
{
SearchSite();
return false;
}
else
return true;
}
function SearchSite()
{
document.location.href='search_result.aspx?cx=006309227296184785814:f9bcc86z5hm&cof=FORID%3A11&ie=UTF-8&q=' + URLEncode(document.getElementById('q').value) + '&sa=Search';
}
然后创建页面:搜索result.aspx
<div id="cse-search-results"></div>
<script type="text/javascript">
var googleSearchIframeName = "cse-search-results";
var googleSearchFormName = "cse-search-box";
var googleSearchFrameWidth = 600;
var googleSearchDomain = "www.google.com";
var googleSearchPath = "/cse";
</script>
<script type="text/javascript" src="http://www.google.com/afsonline/show_afs_search.js"></script>