[英]How do you get all the links from a page with node puppeteer?
我正在尝试使用node构建Web搜寻器,并遇到了puppeteer程序包,该程序包非常适合我想要的内容。 我的最终结果是收集页面的所有链接,页面的所有文本内容,然后是页面本身的屏幕截图。
我执行了以下操作,它似乎收集了大量链接,但是在实际检查站点时,有一些链接没有收集。
const puppeteer = require('puppeteer');
module.exports = () => {
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://pixabay.com/en/columbine-columbines-aquilegia-3379045/');
await page.screenshot({ path: 'myscreenshot.png', fullPage: true });
let text = await page.$eval('*', el => el.innerText.split(' '));
text = text.map(string => {
return string.replace(/[^\w\s]/gi, '');
});
let hrefs = await page.evaluate(() => {
const links = Array.from(document.querySelectorAll('a'))
return links.map(link => link.href);
});
console.log('done');
await browser.close();
})();
};
例如,以下链接: /go/?t=image-details-shutterstock&id=699165328
在href数组中不存在。 更糟糕的是,这些是引出该站点的链接,是我想要做的确切类型,否则,我只能抓取一个站点。
我的脚本仅显示某些链接是有原因的吗? 查询选择器是否太狭窄或拒绝某些链接?
链接是由onclick
事件生成的,例如保存在data-go
属性中
<a data-go="image-details-shutterstock&id=458320033">
它只需要添加/go/?t=
并获得它
return links.map(link => link.href || link.getAttribute('data-go'));
也有菜单的空白链接,例如
<a><i class="icon icon_menu_user"></i></a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.