使用Axios+Cheerio抓取Discogs页面时无法精准获取艺术家名称
抓取Discogs页面时精准获取艺术家名称的问题
问题详情
我在抓取Discogs网站页面,现有JS代码如下:
const axios = require('axios'); const cheerio = require('cheerio'); const r = 704290; const link = 'https://www.discogs.com/sell/release/'; const link_completo = link + r.toString(); const headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0', 'Referer': 'http://www.discogs.com' }; console.log(link_completo); axios.get(link_completo, { headers }) .then((response) => { const $ = cheerio.load(response.data); const artist = $('h1').text(); console.log('Artist:', artist.trim()); });
目标页面的HTML结构:
<h1 class="title_1q3xW"> <span class="link_15cpV"> <a href="/artist/20991-The-Rolling-Stones" hreflang="en" class="link_1ctor link_15cpV">The Rolling Stones</a> </span> – <!-- -->Black And Blue </h1>
当前代码输出:
Artist: The Rolling Stones – Black And Blue
我想精准拿到艺术家名称"The Rolling Stones",于是把代码里的const artist = $('h1').text();改成const artist = $('.title_1q3xW').text()或者const artist = $('.link_15cpV').text(),但修改后完全没返回结果,求帮忙解决。
测试代码片段:
const artist = $('.link_15cpV').text(); console.log(artist);
<h1 class="title_1q3xW"><span class="link_15cpV"> <a href="/artist/20991-The-Rolling-Stones" hreflang="en" class="link_1ctor link_15cpV">The Rolling Stones</a></span> – <!-- -->Black And Blue</h1> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
解决方案
问题根源是Discogs用了动态生成的类名(比如title_1q3xW、link_15cpV这类带随机后缀的类),这些类名会随时变化,直接用它们定位元素自然抓不到。
可以换两种更稳定的方式获取:
方案1:通过艺术家链接的属性定位
利用<h1>下指向艺术家页面的<a>标签,通过href前缀来精准定位:
const artist = $('h1 a[href^="/artist/"]').text().trim();
方案2:拆分<h1>文本内容
<h1>里的艺术家和专辑名用–分隔,直接拆分文本提取前半部分:
const h1Text = $('h1').text().trim(); const artist = h1Text.split('–')[0].trim();
修改后的完整代码:
const axios = require('axios'); const cheerio = require('cheerio'); const r = 704290; const link = 'https://www.discogs.com/sell/release/'; const link_completo = link + r.toString(); const headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0', 'Referer': 'http://www.discogs.com' }; console.log(link_completo); axios.get(link_completo, { headers }) .then((response) => { const $ = cheerio.load(response.data); // 选其中一种方案即可 const artist = $('h1 a[href^="/artist/"]').text().trim(); // const h1Text = $('h1').text().trim(); // const artist = h1Text.split('–')[0].trim(); console.log('Artist:', artist); });
注意事项
Discogs这类网站常用动态类名反爬,所以尽量别依赖带随机后缀的类选择器。优先用元素结构、固定属性(比如href前缀)这类不会轻易变化的特征来定位元素。
内容的提问来源于stack exchange,提问作者dnnywld
相关产品推荐
相关产品推荐

