如何选择axios自带的元素?

我正在尝试使用 axios 选择来自 http 请求的元素


const axios = require('axios');


axios.get('https://example.com/')

    .then((response) => {

        console.log(response);

    });

响应看起来像:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta name="description" content="example">

    <title>Example</title>

</head>

<body>

    <div class="container">

        <div class="row">

            <img class="image" src="example.png" alt="example">

            <div class="col">Example</div>

        </div>

    </div>

</body>

</html>

即我想选择.image的 src 属性。


我想在response. 如果我们能用 jQuery 做到这一点,那就太好了。我想访问它的属性和 html 内容。


蝴蝶刀刀
浏览 152回答 3
3回答

慕桂英3389331

尝试使用cheerio(专为服务器设计的核心 jQuery 实现)axios&nbsp; &nbsp;.get(url)&nbsp; &nbsp;.then(response => {&nbsp; &nbsp; &nbsp;const $ = cheerio.load(response.data);&nbsp; &nbsp; &nbsp;const image = $('img')&nbsp;&nbsp; &nbsp; &nbsp;$("img").each((i, elem) => {&nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; &nbsp;...&nbsp; &nbsp;})

婷婷同学_

再见,看这个例子:console.log($( "div.col" ).text())console.log($( "img" ).attr('src'))<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <meta name="description" content="example">&nbsp; &nbsp; <title>Example</title></head><body>&nbsp; &nbsp; <div class="container">&nbsp; &nbsp; &nbsp; &nbsp; <div class="row">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img src="example.png" alt="example">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="col">Example</div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></body></html>我得到了 div 的内部col文本$( "div.col" ).text()。要获得一个属性(例如)&nbsp;src,img我已经完成了$( "img" ).attr('src')

慕尼黑8549860

如果您将响应添加到文档,然后尝试获取事件,那么您可以尝试以下方法$('body').on('click', '.col', function(){&nbsp; &nbsp; // do your work})如果您想即时选择任何元素,请使用以下方法$(response).find('.col')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript