I am fetching all anchor tag links via web scraping and want to print all links with space between them so while console I used "\n" but it is not making space after end of first link and second link text start without space.
Code:
(async() => {
const html = await axios.get('https://www.xyz');
const $ = await cheerio.load(html.data);
let data = []
$(".div-previews").each((i, elem) => {
console.log('data::', $(elem).find(".header-text a").text() + "\n"); // show links with space between them
})();
})
This should work better - I replaced your each and find
(async() => {
const html = await axios.get('https://www.xyz');
const $ = await cheerio.load(html.data);
console.log('data::',
$(".div-previews .header-text a")
.map(function() { return this.textContent })
.get()
.join("\n") // or .join(" ")
)
})
Example
console.log('data::',
$(".div-previews .header-text a")
.map(function() {
return this.textContent
})
.get()
.join("\n") // or .join(" ")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="div-previews">
<div class="header-text">
<a href="">Link 1</a>
</div>
</div>
<div class="div-previews">
<div class="header-text">
<a href="">Link 2</a>
</div>
</div>
<div class="div-previews">
<div class="header-text">
<a href="">Link 3</a>
<a href="">Link 4</a>
</div>
</div>