正在解析来自 Google 条新闻的值

Parsing values from Google news

来自 Google 新闻 我正在尝试解析结果。例如,从搜索“latest movie releases”中解析标题和文本,这里是 URL:

https://www.google.com/search?client=firefox-b-d&tbm=nws&sxsrf=ALeKk01qAUzdE7UzK9aWPL9MYALHEk6aiQ%3A1599313588168&ei=tJZTX6vwCdWr1fAP6eGiyAk&q=latest+movie+releases&oq=latest+movie+releases&gs_l=psy-ab.3...299098.305542.0.305681.31.25.3.2.2.0.161.1719.22j3.25.0....0...1c.1.64.psy-ab..1.13.704...0j33i10k1.0.9TgaNbbee40

结果似乎在 id 中使用了#rso:

但是 $('#rso').each 上的迭代器是空的。为了遍历搜索结果的 div,我应该 select 什么 id 或 css 元素?

迭代器代码:

$('#rso').each(function (i, element) {
    console('div level 1')
    var title = $(this).find('.r').text();
    var link = $(this).find('.r').find('a').attr('href').replace('/url?q=', '').split('&')[0];
    var text = $(this).find('.st').text();
    var img = $(this).find('img.th').attr('src');
    savedData.push({
      title: title,
      link: link,
      text: text,
      img: img
    });
  });

试试这个:

$('#rso > div').each(...

您应该使用 $$ 而不是

$$('#rso > div')

参考

Console Utilities API Reference

$(selector) is alias to document.querySelector()

$$(selector) is alias to document.querySelectorAll()

你能试试这个吗

let data = {};
document.querySelectorAll("#rso").forEach(elem => {
    let hrefs = []; 
    let imgs = [];
    elem.querySelectorAll("a").forEach(aElem => {
        hrefs.push({href: aElem.getAttribute("href")});    
    });
    elem.querySelectorAll("img").forEach(iElem => {
        imgs.push({src: iElem.getAttribute("src")});        
    });
    data.links = hrefs;
    data.images = imgs;
})

请注意,每张卡片都有两张图片,一张是左侧图标的缩略图,另一张是实际图片。 所以图片列表的长度将是 2 * 链接列表的长度。