Greasemonkey刮刀代码抓取字母而不是单词?

时间:2016-12-08 00:32:47

标签: javascript jquery web-scraping greasemonkey

我正在编写一个简单的用户脚本,用于删除一些体育数据并将其放在页面顶部的表格中。但是,不是将每个团队名称放在自己的行中,而是将每个单词分成单个字母并将它们放在行中。

来源HTML:

<span class="team-title" id="firstTeamName">Oakland Raiders</span>

示例代码:

$(document).ready(function () {

$('#navFixed').after('<table id="tbone"></table>'); //navFixed is just an element at the top of the page

var team1 = $('span#firstTeamName').text();

for (var i = 0; i < team1.length; i++) {
    var txt = $('<tr><td></td></tr>').text(team1[i]);
    $('#tbone').append(txt);
    }
});

示例HTML输出:

<table id="tbone">
    <tr><td>O</td></tr>
    <tr><td>a</td></tr>
    <tr><td>k</td></tr>
    <tr><td>l</td></tr>
    ...
</table>

理想输出:

<table id="tbone">
<tr>Oakland Raiders</tr>
</table>

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

.text() returns a string,这就是你想要的。通过字符串循环产生单个字母。不要这样做。 ;)

我怀疑你想要在团队中循环。通过选择所有.team-title节点并使用jQuery's .each()循环遍历它们来实现这一点 看到这段代码:

&#13;
&#13;
$("button").click ( function () {
    //--- Greasemonkey javascript follows...
    var targTble    = $('<table id="tbone"></table>').insertAfter ("#navFixed");
    var teams       = $(".team-title");

    teams.each ( function () {
        var teamName = $(this).text ().trim ();  //-- Always beware of whitespace
        targTble.append ('<tr><td>' + teamName + '</td></tr>');
    } );
    //--- End of Greasemonkey javascript.
    this.disabled = true;
} );
&#13;
.team-title {background: #ddd; font-size: 80%;}
table {border-collapse: collapse;}
table, td {border: 1px solid green;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span id="navFixed"></span><br>
<span class="team-title" id="firstTeamName">Oakland Pirates</span><br>
<span class="team-title" id="firstTeam_02"> San Fran Gold diggers</span><br>
<span class="team-title" id="firstTeam_03"> Dallas Cow pokes</span><br>
<button>Run Greasemonkey code</button>
&#13;
&#13;
&#13;