我正在参加中秋创意投稿大赛,详情请看:中秋创意投稿大赛
中秋节将至,那么你知道大家的最爱哪一种口味的月饼吗?你知道那款月饼的销量遥遥领先吗?接下来就一起来看看如何通过selenium抓取某东月饼的销量排行榜吧
配置环境
1、初始化项目
npm init -y
2、下载对应的webdrive
Browser | Component |
---|---|
Chrome | chromedriver(.exe) |
Internet Explorer | IEDriverServer.exe |
Edge | MicrosoftWebDriver.msi |
Firefox | geckodriver(.exe) |
Opera | operadriver(.exe) |
Safari | safaridriver |
根据自己的环境进行下载,将下载好的压缩包解压到项目的根目录不需要安装,各个浏览器的版本和dirver的版本的选择需要相近,不能盲目选择最新的版本,否则会出现意想不到的bug,建议最好将浏览器升级至最新的稳定版本并选择对应的包。
3、下载依赖
npm install selenium-webdriver
4、建立一个index.js
文件,用来编写接下来的逻辑
准备项目完成之后,接来下可以跑一个demo来测试一下,代码在创建的index.js
中编写
首先按需引入selenium-webdrivert
const { Builder, By, Key } = require("selenium-webdriver");
接下来变开始逻辑代码的编写
// 所有的操作都在一个 IIFE 中
(async function example() {
// 实例化 driver 对象, chrome 代表使用的浏览器
let driver = await new Builder().forBrowser("chrome").build();
try {
// 打开目标网站地址
await driver.get("https://cn.bing.com/");
// 选择标签,输入关键字 并搜索
await driver.findElement(By.name("q")).sendKeys("webdriver", Key.RETURN);
// 断言页面 title
await driver.wait(until.titleIs("webdriver - 国内版 Bing"), 1000);
} finally {
// 自动关闭浏览器
// await driver.quit();
}
})();
抓取月饼销售
接下来便看一下如何利用selenium抓取某东的月饼销量
首先需要按需引入需要的函数和类,编写一个自执行函数,接下来的爬取行为都在IIFE中
const { Builder, By, Key } = require("selenium-webdriver");
// 所有的操作都在一个 IIFE 中
(async function example() {
// to do ...
})();
接下来便通过打开某东网站,并通过输入框输入月饼关键字进行搜索
try {
// 打开目标网站地址
await driver.get("https://www.jd.com/");
// 选择标签,输入关键字 并搜索
await driver.findElement(By.id("key")).sendKeys("月饼", Key.RETURN);
} finally {
// 自动关闭浏览器;
await driver.quit();
}
等待页面的搜索结果渲染,展示的便是我们期望的样子
结果展示之后,通过页面可以看到此时展示的是按照综合筛选条件过滤的数据,而期望的是爬取销售量数据
接下来通过css选择器选择页面上销量按钮并点击,获得销售量排名的数据
await driver
.findElement(By.css("#J_filter .f-line.top .f-sort a:nth-of-type(2)"))
.click();
至此页面已经渲染了符合我们预期的数据,接下来便是通过分析页面进行数据的抓取
const getMoonPriceList = async () => {
// 数据存储
const moonList = [];
// 获取到每一个 展示的card
const _li = await driver.findElements(
By.css("#J_goodsList .gl-warp .gl-item")
);
for (let i = 0, len = _li.length; i < len; i++) {
// 获取每一项数据
const itemInfo = _li[i];
// 价格
const price = await itemInfo.findElement(By.css(".p-price i")).getText();
// 标题
const title = await itemInfo.findElement(By.css(".p-name i")).getText();
// 评论数
const comment = await itemInfo
.findElement(By.css(".p-commit a"))
.getText();
moonList.push({
price,
title,
comment,
});
}
console.log("_li length", moonList);
};
getMoonPriceList()
抓取到的部分数据如图:
整个抓包的部分过程: