【问题标题】:Scraping a url value using contains and Cheeriogs使用 contains 和 Cheerogs 抓取 url 值
【发布时间】:2021-10-05 05:09:26
【问题描述】:

我使用 Cheeriogs 库进行抓取:

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);

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

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

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

那没用。我应该如何使用contains 来满足这个需求?

添加信息:

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

图像到元素

【问题讨论】:

  • 你能澄清你的问题吗?您当前的 css 不可靠怎么办?你能告诉我们你期待什么输出吗?我看到有两个节点符合你的规则,你想要这两个值吗? '/en/predictions-tips-wealdstone-solihull-moors-1455115', '/en/predictions-tips-northampton-walsall-fc-1474257'?你试过简单的a.tnmscn::attr(href)吗?
  • 非常感谢您提出疑问,我添加了更多有关所需值位置的详细信息。 @Granitosaurus

标签: google-apps-script web-scraping cheerio


【解决方案1】:

在你的情况下,下面的选择器怎么样?

发件人:

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
  • 在上述选择器中,a 标记和atnmscnhref 的起始文本为/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
    

参考资料:

【讨论】:

  • 你好朋友@Tanaike,你的回答解决了我的问题,但是你对恢复值的问题感到怀疑,我在问题中添加了一个关于我对收集正确的href缺乏信心的问题。
  • @Brondby IF 感谢您的回复。很高兴您的问题得到解决。
猜你喜欢
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 2019-12-26
相关资源
最近更新 更多