R爬虫之京东商城手机信息批量获取
人手一部智能手机的移动互联网时代,智能手机对很多人来说,它就像我们身上生长出来的一个器官那样重要。如果你不能对各大品牌的『卖点』和『受众』侃上一阵,很可能会被怀疑不是地球人。
今天我们来探索一下,如何从『京东商城』爬取各大品牌的手机信息。
1.预备知识
R爬虫需要掌握的技能包括:
基本的网页知识,如html,XML文件的解析
分析XPath
使用网页开发工具
异常捕捉的处理
字符串的处理
正则表达式的使用
数据库的基本操作
不过不要担心,目前只需要掌握前三项技能,即可开始练习。
前三项技能的掌握可以参考 Automated Data Collection with R 一书。正常情况下,一天之内大致即可掌握。
2.页面分析
(待完善)
3.提取各大品牌的链接
#### packages we need ####
## ----------------------------------------------------------------------- ##
require(stringr)
require(XML)
require(RCurl)
library(Rwebdriver)
setwd("JDDownload")
BaseUrl<-"http://search.jd.com"
quit_session()
start_session(root = "http://localhost:4444/wd/hub/",browser = "firefox")
# post Base Url
post.url(url = BaseUrl)
SearchField<-element_xpath_find(value = '//*[@id="keyword"]')
SearchButton<-element_xpath_find(value = '//*[@id="gwd_360buy"]/body/div[2]/form/input[3]')
#keyword for search
keywords<-'手机'
element_click(SearchField)
keys(keywords)
element_click(SearchButton)
Sys.sleep(1)
#test
get.url()
pageSource<-page_source()
parsedSourcePage<-htmlParse(pageSource, encoding = 'UTF-8')
## Download Search Results
fname <- paste0(keywords, " SearchPage 1.html")
writeLines(pageSource, fname)
#get all the brand url
Brand<-'//*[@id="J_selector"]/div[1]/div/div[2]/div[3]/ul/li/a/@href'
BrandLinks<-xpathSApply(doc = parsedSourcePage, path = Brand)
View(data.frame(BrandLinks))
BrandLinks<-sapply(BrandLinks,function(x){
paste0(BaseUrl,"/",x)
})
save(BrandLinks,file = 'BrandLinks.rda')
4.访问每个品牌的页面,抓取每个品牌下的商品链接
##############Function 1 #################################3##
### 对各品牌的手机页面进行抓取 ########3#
getBrandPage<-function(BrandUrl,foreDownload = T){
#获取某品牌搜索页面
post.url(BrandUrl)
Brand_pageSource<-page_source()
#parse
parsedSourcePage<-htmlParse(Brand_pageSource, encoding = 'UTF-8')
#get brand name
BrandNamePath<-'//*[@id="J_crumbsBar"]/div[2]/div/a/em'
BrandName<-xpathSApply(doc = parsedSourcePage, path = BrandNamePath, fun = xmlValue)
#Save the page
BrandPageName<-paste0(BrandName,'_PageSource.html')
#Create a file
if(!file.exists(BrandName)) dir.create(BrandName)
# save
writeLines(text = Brand_pageSource, con = paste0(BrandName,'/',BrandPageName))
# get the product page url
#path
Brand_AllProductPath<-'//*[@id="J_goodsList"]/ul/li/div/div[4]/a/@href'
#url
Brand_AllProductLinks<-xpathSApply(doc = parsedSourcePage, path = Brand_AllProductPath)
# #remove some false url
# FalseLink<-grep(x = Brand_AllProductLinks,pattern = 'https',fixed = TRUE)
# Brand_AllProductLinks<-Brand_AllProductLinks[-FalseLink]
# add a head
Brand_AllProductLinks<-str_c('http:',Brand_AllProductLinks)
#save and return the url
save(Brand_AllProductLinks,file = paste0(BrandName,'_AllProductLinks.rda'))
return(Brand_AllProductLinks)
}
# test
BrandUrl<-BrandLinks[1]
getBrandPage(BrandUrl)
#get all the links
Brand_ProductLink<-list()
for(i in 1:length(BrandLinks)){
Sys.sleep(10)
Brand_ProductLink[[i]]<-getBrandPage(BrandUrl = BrandLinks[i])
}
#clean the links
All_ProductLink<-lapply(Brand_ProductLink,function(x){
TrueLink<-grep(x = x,pattern = 'http://item.jd.com/',fixed = TRUE,value = FALSE)
return(x[TrueLink])
})
# save the links
save(All_ProductLink,file = 'All_ProductLink.rda')
5.访问每个商品页面,提取有用信息
我们初步提取如下指标:标题(Title),卖点(KeyCount),价格(Price),评论数(commentCount),尺寸(Size),后置摄像头像素(BackBit),后置摄像头像素(ForwardBit),核数(Core),分辨率(Resolution),品牌(Brand),上架时间(onSaleTime).
#################################################
######## Function2 :访问每个商品页面,提取有用信息 ########
Product<-function(ProductLink){
post.url(ProductLink)
Sys.sleep(4)
# get the page
Product_pageSource<-page_source()
#parse
Parsed_product_Page<-htmlParse(Product_pageSource, encoding = 'UTF-8')
# get title,,key count,price,CommentCount and so on
#PATH
TitlePath<-'//*[@id="name"]/h1'
KeyCountPath<-'//*[@id="p-ad"]'
PricePath<-'//*[@id="jd-price"]'
commentCountPath<-'//*[@id="comment-count"]/a'
SizePath<-'//*[@id="parameter1"]/li[1]/div/p[1]'
BackBitPath<-'//*[@id="parameter1"]/li[2]/div/p[1]'
ForwardBitPath<-'//*[@id="parameter1"]/li[2]/div/p[2]'
CorePath<-'//*[@id="parameter1"]/li[3]/div/p[1]'
NamePath<-'//*[@id="parameter2"]/li[1]'
CodePath<-'//*[@id="parameter2"]/li[2]'
BrandPath<-'//*[@id="parameter2"]/li[3]'
onSaleTimePath<-'//*[@id="parameter2"]/li[4]'
ResolutionPath<-'//*[@id="parameter1"]/li[1]/div/p[2]'
Title<-xpathSApply(doc = Parsed_product_Page,path = TitlePath,xmlValue)
KeyCount<-xpathSApply(doc = Parsed_product_Page,path = KeyCountPath,xmlValue)
Price<-xpathSApply(doc = Parsed_product_Page,path = PricePath,xmlValue)
commentCount<-xpathSApply(doc = Parsed_product_Page,path = commentCountPath,xmlValue)
Size<-xpathSApply(doc = Parsed_product_Page,path = SizePath,xmlValue)
BackBit<-xpathSApply(doc = Parsed_product_Page,path = BackBitPath,xmlValue)
ForwardBit<-xpathSApply(doc = Parsed_product_Page,path = ForwardBitPath,xmlValue)
Core<-xpathSApply(doc = Parsed_product_Page,path = CorePath,xmlValue)
Name<-xpathSApply(doc = Parsed_product_Page,path = NamePath,xmlValue)
Code<-xpathSApply(doc = Parsed_product_Page,path = CodePath,xmlValue)
Resolution<-xpathSApply(doc = Parsed_product_Page,path = ResolutionPath,xmlValue)
Brand<-xpathSApply(doc = Parsed_product_Page,path = BrandPath,xmlValue)
onSaleTime<-xpathSApply(doc = Parsed_product_Page,path = onSaleTimePath,xmlValue)
# 整理成data frame
mydata<-data.frame(Title = Title,KeyCount = KeyCount, Price = Price,
commentCount = commentCount, Size = Size, BackBit = BackBit,
ForwardBit = ForwardBit, Core = Core, Name = Name,Code = Code,
Resolution = Resolution,
Brand = Brand, onSaleTime = onSaleTime)
#save the page
FileName<-paste0('Product/',Brand,Code,'_pageSource.html')
writeLines(text = Product_pageSource,con = FileName)
#return the data
return(mydata)
}
# test
quit_session()
start_session(root = "http://localhost:4444/wd/hub/",browser = "firefox")
load(file = 'All_ProductLink.rda')
ProductLink1<-All_ProductLink[[40]][1]
testData<-Product(ProductLink = ProductLink1)
#定义tryCatch
mySpider<-function(ProductLink){
out<-tryCatch(
{
message('This is the try part:')
Product(ProductLink = ProductLink)
},
error=function(e){
message(e)
return(NA)
},
finally = {
message("The end!")
}
)
return(out)
}
## loop
# get all data
ProductInformation<-list()
k <-0
for(i in 1:length(All_ProductLink)){
for(j in 1:length(All_ProductLink[[i]])){
k<-k+1
ProductInformation[[k]]<-mySpider(ProductLink = All_ProductLink[[i]][j])
}
}
# save my data
MobilePhoneInformation<-do.call(rbind,ProductInformation)
View(MobilePhoneInformation)
save(MobilePhoneInformation,file = 'MobilePhoneInformation.rda')
nrow(na.omit(MobilePhoneInformation))
View(MobilePhoneInformation)
最终,获得800多行的信息,除去缺失值,剩下600多行数据,还不赖。 最后的数据可以在这里获得。
不过,数据还需要进一步清洗方能进行分析。
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
“最近复购率一直在下降,我们的营销力度不小啊,为什么用户还是走了?” “是不是广告投放的用户质量不高?还是我们的产品问题 ...
2025-02-21以下文章来源于数有道 ,作者数据星爷 SQL查询是数据分析工作的基础,也是CDA数据分析师一级的核心考点,人工智能时代,AI能为 ...
2025-02-19在当今这个数据驱动的时代,几乎每一个业务决策都离不开对数据的深入分析。而其中,指标波动归因分析更是至关重要的一环。无论是 ...
2025-02-18当数据开始说谎:那些年我们交过的学费 你有没有经历过这样的场景?熬了三个通宵做的数据分析报告,在会议上被老板一句"这数据靠 ...
2025-02-17数据分析作为一门跨学科领域,融合了统计学、编程、业务理解和可视化技术。无论是初学者还是有一定经验的从业者,系统化的学习路 ...
2025-02-17挖掘用户价值本质是让企业从‘赚今天的钱’升级为‘赚未来的钱’,同时让用户从‘被推销’变为‘被满足’。询问deepseek关于挖 ...
2025-02-17近来deepseek爆火,看看deepseek能否帮我们快速实现数据看板实时更新。 可以看出这对不知道怎么动手的小白来说是相当友好的, ...
2025-02-14一秒精通 Deepseek,不用找教程,不用买资料,更不用报一堆垃圾课程,所有这么去做的,都是舍近求远,因为你忽略了 deepseek 的 ...
2025-02-12自学 Python 的关键在于高效规划 + 实践驱动。以下是一份适合零基础快速入门的自学路径,结合资源推荐和实用技巧: 一、快速入 ...
2025-02-12“我们的利润率上升了,但销售额却没变,这是为什么?” “某个业务的市场份额在下滑,到底是什么原因?” “公司整体业绩 ...
2025-02-08活动介绍 为了助力大家在数据分析领域不断精进技能,我们特别举办本期打卡活动。在这里,你可以充分利用碎片化时间在线学习,让 ...
2025-02-071、闺女,醒醒,媒人把相亲的带来了。 我。。。。。。。 2、前年春节相亲相了40个, 去年春节相亲50个, 祖宗,今年你想相多少个 ...
2025-02-06在数据科学的广阔领域中,统计分析与数据挖掘占据了重要位置。尽管它们常常被视为有关联的领域,但两者在理论基础、目标、方法及 ...
2025-02-05在数据分析的世界里,“对比”是一种简单且有效的方法。这就像两个女孩子穿同一款式的衣服,效果不一样。 很多人都听过“货比三 ...
2025-02-05当我们只有非常少量的已标记数据,同时有大量未标记数据点时,可以使用半监督学习算法来处理。在sklearn中,基于图算法的半监督 ...
2025-02-05考虑一种棘手的情况:训练数据中大部分样本没有标签。此时,我们可以考虑使用半监督学习方法来处理。半监督学习能够利用这些额 ...
2025-02-04一、数学函数 1、取整 =INT(数字) 2、求余数 =MOD(除数,被除数) 3、四舍五入 =ROUND(数字,保留小数位数) 4、取绝对值 =AB ...
2025-02-03作者:CDA持证人 余治国 一般各平台出薪资报告,都会哀嚎遍野。举个例子,去年某招聘平台发布《中国女性职场现状调查报告》, ...
2025-02-02真正的数据分析大神是什么样的呢?有人认为他们能轻松驾驭各种分析工具,能够从海量数据中找到潜在关联,或者一眼识别报告中的数 ...
2025-02-01现今社会,“转行”似乎成无数职场人无法回避的话题。但行业就像座围城:外行人看光鲜,内行人看心酸。数据分析这个行业,近几年 ...
2025-01-31