我正在做一个小项目,但我似乎陷入了困境。希望你们中的一些伟大的人能够帮助我解决这个问题。
我正在尝试找出一种简单有效的方法,从搜索引擎结果页面中挑选一个或多个RANDOM字词。这是我坚持的部分。
选择之后,我会将单词存储在一个变量中。
搜索结果如下所示:http://i54.tinypic.com/34fllw1.png
提前致谢。任何提示/帮助将不胜感激!
编辑:有没有办法可以挑出一串连续的随机长度的单词?答案 0 :(得分:1)
以下是适用于google.com的示例
//get the text
var text=document.getElementById('rso').textContent;
//find the words
var words=text.match(/\b([a-z]{3,})\b/gi);
//pick a word
alert(words[Math.floor(words.length*Math.random())]);
搜索结果列在ID为“rso”的元素中 正则表达式匹配由至少3个字符组成的字符串a-z
答案 1 :(得分:1)
Google用于描述的类是st
,所以这是Dr.Molle解决方案的改进:
//get the text
var text=document.querySelector(".st"),output=[];
//loop through the descriptions
for(var i=0;i<text.length;i++){
//find the words
var words=text[i].innerText.match(/\b([a-z]{3,})\b/gi);
//push the array to the output variable
output.push.apply(output,words);
}
//pick a word
var theWord=output[Math.floor(Math.random()*output.length)];
//now theWord has a randomly chosen word
alert(theWord);
并挑出几句话:
//change the 10 to the max number of words
var amount=Math.floor(Math.random()*10),theWords="";
//get the text
var text=document.querySelector(".st"),output=[];
//loop through the descriptions
for(var i=0;i<text.length;i++){
//find the words
var words=text[i].innerText.match(/\b([a-z]{3,})\b/gi);
//push the array to the output variable
output.push.apply(output,words);
}
//pick a word
var theNumber=Math.floor(Math.random()*output.length);
//loops the code the number of times randomly chosen
for(var i=0;i<amount;i++){
//add on to the string
theWords+=(i==0?"":" ")+output[theNumber+i];
}
//now theWords has a random number of consecutive words
alert(theWords);
广告@米
答案 2 :(得分:0)
这是一个完整的Greasemonkey脚本,可以从描述中抓取任意数量的随机单词,并且可以更好地处理各种Google搜索页面(它们会稍微改变DOM,具体取决于页面的获取方式。)< / p>
// ==UserScript==
// @name _RandomWord from results
// @include http://www.google.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
// ==/UserScript==
function GrabRandomWords () {
/*--- Google search results are wrapped in a list with the id "rso".
Here, we want just the descriptions in the results, so we know
that title and link tag tags can be excluded.
(Alas, Google's search results pages vary quite a bit in the
detailed structure of their HTML.)
*/
var descriptText = $("#rso li *:not(a,h1,h2,h3)").text ();
//--- Split into words. Change the "{1,}", if short words like "a" are to be excluded.
var words = descriptText.match (/\b(\w{1,})\b/g);
//--- Pick 5 random words and store them in an array.
if (words) {
var ourRandWords = [];
for (var J = 0; J < 5; ++J)
ourRandWords.push ( words[ Math.floor (words.length * Math.random() ) ] );
alert (ourRandWords);
}
}
//--- We must wait until page has fully loaded, because the results are usually Ajaxed in.
window.addEventListener ("load",
function () {
/*--- Page is "loaded", but results are still not in, still need a short delay.
Note that listening for DOMSubtreeModified doesn't seem to work well.
*/
setTimeout (function() { GrabRandomWords (); }, 666);
},
false
);