本文实现在京东搜索栏中自动输入关键字搜索商品(以“毛衣”为例),并自动采集搜索的内容,采集内容包含商品基本信息及价格,显示在表中,效果如下图所示:
页面分析:
1 搜索栏及搜索按钮
2 商品列表
3 下一页按钮
主要代码如下:
1.关键字输入及搜索按钮的点击
var keyword_element = document.getElementById('key');
var search_elements = document.querySelectorAll('#search-2014 .form button');
if (keyword_element && search_elements && search_elements.length > 0){
//设置关键字
keyword_element.focus();
keyword_element.dispatchEvent(new Event('keydown',{bubbles:true}));
keyword_element.value = 'mykeyword';
keyword_element.dispatchEvent(new Event('input',{bubbles:true}));
keyword_element.dispatchEvent(new Event('change',{bubbles:true}));
//点击搜索按钮
search_elements[0].click();
};
2.商品信息的获取
//获取商品数据(商品名称和商品价格)
var price = '',name = '',info='';
var price_element = null,name_element = null;
var goods_list = document.querySelectorAll('#J_goodsList .gl-warp .gl-item');
if (goods_list && goods_list.length > 0){
for(var i = 0;i < goods_list.length;i ++){
//商品价格
price = '';
price_element = goods_list[i].querySelectorAll('.p-price i');
if (price_element && price_element.length > 0)
price += price_element[0].innerText;
//商品名
name = '';
name_element = goods_list[i].querySelectorAll('.p-name em');
if (name_element && name_element.length > 0)name += name_element[0].innerText;
}
}
3.自动滚动页面
var scroll_length = 0; //已经翻滚的长度
var scroll_frequency = 20; //控制翻滚频次
var scroll_timer = setInterval(function(){
var scroll_height = document.body.scrollHeight;//重新获取还需要翻滚的长度
if(document.documentElement.clientHeight + scroll_length >= scroll_height ){
clearInterval(scroll_timer);
scroll_timer = null;
else {
scroll_length += scroll_height / scroll_frequency;
document.documentElement.scrollTop = scroll_length;
})
var next_element = document.querySelectorAll('#J_bottomPage .p-num .pn-next');
if (next_element)next_element[0].click();