代码之家  ›  专栏  ›  技术社区  ›  Digital Farmer

使用contains和Cheeriogs删除url值

  •  0
  • Digital Farmer  · 技术社区  · 4 年前

    https://github.com/tani/cheeriogs

    这是我需要收集值的元素 href :

    <a class="tnmscn" itemprop="url" href="/en/predictions-tips-wealdstone-solihull-moors-1455115">
    

    const contentText = UrlFetchApp.fetch(url).getContentText();
    const $ = Cheerio.load(contentText);
    
    const scrapurl = $('div.schema > div > div.tnms > div > a.tnmscn');
    const urlmatch = $(scrapurl).attr('href').trim();
    Logger.log(urlmatch);
    

    但这并不可靠,因为我担心最终会在网站上改变位置并收集其他链接,而不是出现在该位置可点击元素中的链接:

    enter image description here

    所以我想让它更安全,所以我尝试使用:

    div.schema > div > div.tnms > div > a:contains("/en/predictions-tips")
    

    那没用。我应该如何使用 contains 为了这个需要?

    添加信息:

    页面链接
    https://www.forebet.com/en/teams/wealdstone

    图像到元素

    enter image description here

    0 回复  |  直到 4 年前
        1
  •  1
  •   Tanaike    4 年前

    在您的情况下,以下选择器如何?

    发件人:

    const scrapurl = $('div.schema > div > div.tnms > div > a.tnmscn');
    

    致:

    const scrapurl = $('a.tnmscn[href^="/en/predictions"]');
    

    const scrapurl = $('div.schema > div > div.tnms > div > a.tnmscn[href^="/en/predictions"]');
    

    const scrapurl = $('div.schema > div > div.tnms > div > a[href^="/en/predictions"]');
    
    • /en/predictions-tips-wealdstone-solihull-moors-1455115 已检索。
    • href 在标签中 a A. 和全班同学一起 tnmscn /en/predictions

    但是,从您使用的URL中检索到2个值。这一点我已经提过了 Granitosaurus's comment

    如果要检索2个值,那么下面的修改如何?

    修改脚本:

    const url = "https://www.forebet.com/en/teams/wealdstone";
    const contentText = UrlFetchApp.fetch(url).getContentText();
    const $ = Cheerio.load(contentText);
    const scrapurl = $('div.schema > div > div.tnms > div > a.tnmscn[href^="/en/predictions"]'); // and a.tnmscn[href^="/en/predictions"]
    $(scrapurl).each(function() {
      const urlmatch = $(this).attr('href');
      console.log(urlmatch);
    });
    
    • 运行此脚本时,将获得以下结果。

        /en/predictions-tips-wealdstone-solihull-moors-1455115
        /en/predictions-tips-crawley-town-leyton-orient-1474259
      

    推荐文章