我正在尝试通过node.js中的木偶操纵者抓取数据
目前,我正在编写一个脚本,它可以抓取well.ca某一部分中的所有数据
现在,以下是我试图通过node.js实现的方法/逻辑
1-前往网站的医药健康部分
2-使用dom选择器通过dom选择器panel-body-content a[href]从.panel-body-content获取href数组,以抓取子部分
3-使用for循环遍历每个链接(子部分)
4对于每个子链接,通过.col-lg-5ths col-md-3 col-sm-4 col-xs-6 a[href]获取值为col-lg-5ths col-md-3 col-sm-4 col-xs-6的每个类的href,从而获得每个产品的另一个href数组
5-遍历小节中的每个产品
6-收集每个产品的数据
目前,我已经编写了上面的大部分代码:
const puppeteer = require('puppeteer');
const chromeOptions = {
headless: false,
defaultViewport: null,
};
(async function main() {
const browser = await puppeteer.launch(chromeOptions);
try {
const page = await browser.newPage();
await page.goto("https://well.ca/categories/medicine-health_2.html");
console.log("::::::: OPEN WELL ::::::::::");
// href attribute
const hrefs1 = await page.evaluate(
() => Array.from(
document.querySelectorAll('.panel-body-content a[href]'),
a => a.getAttribute('href')
)
);
console.log(hrefs1);
const urls = hrefs1
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
await page.goto(url);
}
const hrefs2 = await page.evaluate(
() => Array.from(
document.querySelectorAll('.col-lg-5ths col-md-3 col-sm-4 col-xs-6 a[href]'),
a => a.getAttribute('href')
)
);当我尝试为每个产品的每个href获取一个数组时,在数组中什么也得不到。
如何添加一个嵌套的for循环,以获取每个小节中每个产品的所有href的数组,然后访问每个产品链接?
要获取id为product_grid_link的类.col-lg-5ths col-md-3 col-sm-4 col-xs-6中的所有href,正确的dom选择器是什么?
如果我想添加一个后续循环,通过每个小节中产品的href从每个产品中获取信息,我如何将其嵌入到代码中?
任何帮助都将不胜感激
发布于 2020-07-02 23:38:29
似乎有些链接是重复的,所以最好是收集最终页面的所有链接,删除链接列表中的重复数据,然后再抓取最终页面。(您还可以将最后几页的链接保存在一个文件中,以供以后使用。)此脚本收集5395个链接(已消除重复数据)。
'use strict';
const puppeteer = require('puppeteer');
(async function main() {
try {
const browser = await puppeteer.launch({ headless: false, defaultViewport: null });
const [page] = await browser.pages();
await page.goto('https://well.ca/categories/medicine-health_2.html');
const hrefsCategoriesDeduped = new Set(await page.evaluate(
() => Array.from(
document.querySelectorAll('.panel-body-content a[href]'),
a => a.href
)
));
const hrefsPages = [];
for (const url of hrefsCategoriesDeduped) {
await page.goto(url);
hrefsPages.push(...await page.evaluate(
() => Array.from(
document.querySelectorAll('.col-lg-5ths.col-md-3.col-sm-4.col-xs-6 a[href]'),
a => a.href
)
));
}
const hrefsPagesDeduped = new Set(hrefsPages);
// hrefsPagesDeduped can be converted back to an array
// and saved in a JSON file now if needed.
for (const url of hrefsPagesDeduped) {
await page.goto(url);
// Scrape the page.
}
await browser.close();
} catch (err) {
console.error(err);
}
})();https://stackoverflow.com/questions/62689746
复制相似问题