axios 用JS抓取一个站点

svmlkihl  于 2023-08-04  发布在  iOS
关注(0)|答案(1)|浏览(58)

我正在尝试抓取一个网页,下面是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


当我改变路线

const artist = $('h1').text();


准确地得到艺术家的名字(滚石乐队)

const artist = $('.title_1q3xW').text()


我没有得到回应
同:

const artist = $('.link_15cpV').text()


这是我在Stack Overflow中的第一个问题,如果问题可能很傻,请耐心等待。谢谢你的耐心

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>
wj8zmpe1

wj8zmpe11#

如果您只需要位于a标记中的The Rolling Stones
例如:
$('h1 a').text();
可能会起作用。下面是它在浏览器中的JavaScript中的工作方式。

document.getElementById('artist-name').innerText = document.querySelector('h1 a').text;

个字符

相关问题