javascript 在嵌套div中获取span的属性

hmae6n7t  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(187)

新的scraping在这里。我的问题是相当直接的,我试图从跨度类“DFlfde SwHCTb”得到值data-value。然而,我得到未定义的返回。我在下面的代码中犯了什么错误?

const axios = require('axios');
const cheerio = require('cheerio');

const url = 'https://www.google.com/search?q=sgd+myr&spell=1&sa=X&ved=2ahUKEwiStvfn5ozoAhVWH7cAHQJZCpwQBSgAegQIDRAm&biw=960&bih=746';

axios(url)
  .then(response => {
    const html = response.data;
    const $ = cheerio.load(html)
    console.log($('span.DFlfde.SwHCTb').attr('data-value'));
  })
  .catch(console.error);

仅打印console.log($('span.DFlfde.SwHCTb'));

initialize {
  options: {
    withDomLvl1: true,
    normalizeWhitespace: false,
    xml: false,
    decodeEntities: true
  },
  _root: initialize {
    '0': {
      type: 'root',
      name: 'root',
      namespace: 'http://www.w3.org/1999/xhtml',
      attribs: [Object: null prototype] {},
      'x-attribsNamespace': [Object: null prototype] {},
      'x-attribsPrefix': [Object: null prototype] {},
      children: [Array],
      parent: null,
      prev: null,
      next: null
    },
    options: {
      withDomLvl1: true,
      normalizeWhitespace: false,
      xml: false,
      decodeEntities: true
    },
    length: 1,
    _root: [Circular]
  },
  length: 0,
  prevObject: initialize {
    '0': {
      type: 'root',
      name: 'root',
      namespace: 'http://www.w3.org/1999/xhtml',
      attribs: [Object: null prototype] {},
      'x-attribsNamespace': [Object: null prototype] {},
      'x-attribsPrefix': [Object: null prototype] {},
      children: [Array],
      parent: null,
      prev: null,
      next: null
    },
    options: {
      withDomLvl1: true,
      normalizeWhitespace: false,
      xml: false,
      decodeEntities: true
    },
    length: 1,
    _root: [Circular]
  }
}
0yg35tkg

0yg35tkg1#

您的选择器似乎正常。请尝试添加用户代理字符串:

const cheerio = require("cheerio"); // 1.0.0-rc.12

const url = "<your URL";
const ua =
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36";

axios
  .get(url, {headers: {"User-Agent": ua}})
  .then(({data: html}) => {
    const $ = cheerio.load(html);
    console.log($("span.DFlfde.SwHCTb").attr("data-value")); // => 3.280947958
  })
  .catch((err) => console.error(err));

相关问题