Javascript 从html greasemonkey提取信息
所以我想写一个greasemonkey脚本,在一个在线游戏中为我放置瓷砖。我已经找到了放置瓷砖的方法,但是为了扩展脚本,我需要将循环限制在移动的数量上。我想不出从页面的html中提取此信息的最佳方法:Javascript 从html greasemonkey提取信息,javascript,regex,greasemonkey,information-extraction,Javascript,Regex,Greasemonkey,Information Extraction,所以我想写一个greasemonkey脚本,在一个在线游戏中为我放置瓷砖。我已经找到了放置瓷砖的方法,但是为了扩展脚本,我需要将循环限制在移动的数量上。我想不出从页面的html中提取此信息的最佳方法: <h2>5</h2>Level:<font size="4px" color="red"> 1455</font><br><br>Moves:<font size="4px" color="red"> 0</
<h2>5</h2>Level:<font size="4px" color="red"> 1455</font><br><br>Moves:<font size="4px" color="red"> 0</font><br>Total:<font size="4px" color="red"> 688</font><br><br><a href="logout.php">
5Level:1455
移动次数:0
总数:688
移动次数:0
总数:688
当前排名(排名)(名称)(总数)(移动次数),BGCOLOR',FFCC00',宽度,-300,不透明度,95,阴影,真实,阴影宽度,7)“onmouseout=”UnTip()”
1600次中的1530次(96%)
1印度5 795 292
2 5 688 0
3黄色节日47 6
我知道这很难看。问题HTML的格式似乎有点不正确和不完整。所有这些的包含节点是什么 无论如何,为了从糟糕的HTML中提取信息,您可以使用blunt force正则表达式来快速解决问题:
var moves = 0;
var movesMatch = document.body.textContent.match (/Moves:\s*(\d+)(?:\D)/);
if (movesMatch && movesMatch.length > 1) {
moves = parseInt (movesMatch[1], 10);
}
console.log ("The number of moves left is: ", moves);
在这种情况下,这可能有效,但除了最简单的页面外,其他页面都很脆弱(很可能“找到”错误的信息)
最佳过程是使用DOM技术尽可能缩小文本范围:
id
attributes(最佳)或class
names(良好)或attributes(可以)。您希望获得指向所需信息的良好“CSS路径”。这可以提供给querySelector
或jQuery。请注意,Firebug将为您提供一个原始CSS路径,您可以使用它作为开始
例如,对于这样的HTML:
<div id="dress-sizes">
<ul>
<li>
<span class="dSize" data-color="green">13</span>
</li>
<li>
<span class="dSize" data-color="green">8</span>
</li>
</ul>
</div>
在这种情况下,给出的唯一ish节点是注销链接
。这看起来是持久的。也就是说,当站点被修改时,它不太可能发生太大变化。但可能有多个注销链接
因此,对该节点进行键控,这是迄今为止我们对HTML所能做的最好的处理:
var anchorNode = document.querySelector ("a[href='logout.php']");
var siblingText = anchorNode.parentNode.textContent;
var moves = 0;
var movesMatch = siblingText.match (/Moves:\s*(\d+)(?:\D)/);
if (movesMatch && movesMatch.length > 1) {
moves = parseInt (movesMatch[1], 10);
}
console.log ("The number of moves left is: ", moves);
更新:现在已知容器,并且它有一个
id
,请使用:
var containerNode = document.querySelector ("#info");
var siblingText = containerNode.textContent;
var moves = 0;
var movesMatch = siblingText.match (/Moves:\s*(\d+)(?:\D)/);
if (movesMatch && movesMatch.length > 1) {
moves = parseInt (movesMatch[1], 10);
}
console.log ("The number of moves left is: ", moves);
var anchorNode = document.querySelector ("a[href='logout.php']");
var siblingText = anchorNode.parentNode.textContent;
var moves = 0;
var movesMatch = siblingText.match (/Moves:\s*(\d+)(?:\D)/);
if (movesMatch && movesMatch.length > 1) {
moves = parseInt (movesMatch[1], 10);
}
console.log ("The number of moves left is: ", moves);
var containerNode = document.querySelector ("#info");
var siblingText = containerNode.textContent;
var moves = 0;
var movesMatch = siblingText.match (/Moves:\s*(\d+)(?:\D)/);
if (movesMatch && movesMatch.length > 1) {
moves = parseInt (movesMatch[1], 10);
}
console.log ("The number of moves left is: ", moves);