You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法获取指定div选项:Node.js+Cheerio爬取足球网站国家数据问题

嘿,作为新手选Cheerio完全没问题!它轻量灵活,专门用来解析HTML结构,抓这个下拉菜单的国家数据简直是对口工具。我帮你把代码补全优化,再给你唠唠几个关键注意点:

优化后的完整代码
const request = require('request');
const cheerio = require('cheerio');
const cheerioAdv = require('cheerio-advanced-selectors');
// 把高级选择器挂载到Cheerio上才能生效
cheerio = cheerioAdv.wrap(cheerio);

// 配置请求头,模拟浏览器访问避免被网站拦截
const options = {
  url: 'https://uk.soccerway.com/',
  headers: {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
  }
};

request(options, function(err, resp, html) {
  if (err) {
    console.error('请求出错啦:', err);
    return;
  }
  
  if (resp.statusCode !== 200) {
    console.error('请求失败,状态码:', resp.statusCode);
    return;
  }

  const $ = cheerio.load(html);
  
  // 定位"Club Domestic"下拉菜单里的国家项
  // 若抓不到数据,可打开网站F12复制对应元素的CSS选择器替换
  const countries = [];
  $('.dropdown-menu[data-dropdown-current="club-domestic"] li a').each((index, element) => {
    const countryName = $(element).text().trim();
    const countryUrl = $(element).attr('href');
    if (countryName) {
      countries.push({
        name: countryName,
        url: countryUrl
      });
    }
  });

  console.log('抓取到的Club Domestic国家数据:', countries);
});
几个实用提醒
  • 请求头必须加:很多网站会拦截无User-Agent的请求,模拟浏览器UA能大幅降低被拦截概率
  • 选择器要适配实际结构:如果上面的选择器没效果,直接打开网站开发者工具(F12),找到下拉菜单的元素右键复制CSS选择器替换即可
  • 关于request库的小提示:request已经停止维护啦,后续如果遇到问题,可以换成axios或node-fetch,用法相近且更稳定
  • 注意反爬限制:别频繁刷请求,不然可能被封IP,必要时可以加个请求延迟(比如用setTimeout)

内容的提问来源于stack exchange,提问作者Amazingstufff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:00:08