簡體   English   中英

循環遍歷可點擊元素列表並將html寫出到各自的文件

[英]Loop through list of clickable elements and write out the html to respective files

我正在使用jQuery來獲取包含某些關鍵字的元素列表。 我能夠獲取元素列表,但我不知道如何遍歷每個元素,單擊其子元素並下載新加載的頁面。 這是我到目前為止的casperjs代碼:

var casper = require('casper').create({
    clientScripts: ["/var/www/html/project/public/js/jquery-3.3.1.min.js"]
});

var fs = require('fs');

casper.start('https://m.1xbet.co.ke/en/line/Football/', function () {
    var links = casper.evaluate(function () {
        $.expr[":"].contains = $.expr.createPseudo(function (arg) {
            return function (elem) {
                return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
            };
        });
        return $("#events-betting").find("li.events__item_head:contains(World cup)");
    });

    var date = new Date(), year = date.getFullYear(), month = date.getMonth() + 1, day = date.getDate();
    var folderName = year + '-' + month + '-' + day;

    // loop would go here to save each file
    var path = "destination/" + folderName + "/1xbet/worldcup-1";
    fs.write(path + ".html", this.getHTML(), "w");

});

casper.run();

我想點擊鏈接對象上的各個項目 - 它們不是錨標簽,而是可點擊的div,內嵌javascript聽取點擊。

目標是單擊具有我感興趣的某些文本的div,然后一旦單擊,我可以選擇刮取HTML並將其保存在文件中或獲取當前URL; 要么對我的目的都好。 由於可能有多個具有所需文本的div,我想要一種循環遍歷每個並執行相同操作的方法。

這是我感興趣的頁面的一個例子:

https://m.1xbet.co.ke/en/line/Football/

在這種情況下,父元素是:#events-betting和嵌套是具有可點擊div的li標簽列表。

我可以選擇刮取HTML並將其保存在文件中或獲取當前的URL

當然,解決方案對於這個確切的站點非常具體,但是在進行網絡抓取時再次是正常的。

casper.start('https://m.1xbet.co.ke/en/line/Football/', function () {

  var links = casper.evaluate(function () {

    $.expr[":"].contains = $.expr.createPseudo(function (arg) {
      return function (elem) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
      };
    });

    var links = [];
    // Better to scrpape .events__title as it contains data-href attribute
    $("#events-betting").find(".events__title:contains(World cup)").each(function (i, item) {
      var lastPartOfurl = item.getAttribute("data-href");
      lastPartOfurl = lastPartOfurl.split("/");
      links.push("https://m.1xbet.co.ke/en/line/Football/" + item.getAttribute("data-champ") + "-" + lastPartOfurl[1]+'/');
    })

    return links;
  });

  console.log(links);
});

結果:

https://m.1xbet.co.ke/en/line/Football/1536237-FIFA-World-Cup-2018/,https://m.1xbet.co.ke/en/line/Football/1204917-FIFA-World-Cup-2018-Winner/,https://m.1xbet.co.ke/en/line/Football/1518431-FIFA-World-Cup-2018-Special-bets/,https://m.1xbet.co.ke/en/line/Football/1706515-FIFA-World-Cup-2018-Teams-Statistics-Group-Stage/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM