coderLMN / AutomatedDataCollectionWithR

《基于 R 语言的自动化数据采集技术》读者讨论区
28 stars 10 forks source link

P204购物车添加商品后并没有商品信息 #7

Open dayushan opened 7 years ago

dayushan commented 7 years ago
library(RCurl)
library(bitops)
library(XML)
library(stringr)
library(plyr)
info<-debugGatherer()
handle<-getCurlHandle(  cookiejar="",
                followlocation=TRUE,
                autoreferer=TRUE,
                debugfunc=info$update,
                verbose=TRUE,
                httpheader=list(
                    from="eddie@r-datacollection.com",
                    'user-agent'=str_c(R.version$version.string,",",R.version$platform)
    )
)
###在R里使用cookie的总体方法是依赖于RCurl的cookie管理功能,它会在连续的请求中重复使用已激活cookie管理的句柄。
###9.1.8.1向在线购物车添加商品
###最有可能需要cookie支持的是访问需要登录的网页
###Biblio在线书店是专门查找并购买二手、珍惜、绝版书籍的
###每次点击add to cart按钮选中一本书放进购物车,都会重定向到购物车(http://www.biblio.com/cart.php)
search_url<-"http://www.biblio.com/search.php?keyisbn=data"
cart_url<-"http://www.biblio.com/cart.php"
##下一步,我们要下载搜索结果页面,然后把它解析并保存到search_page
search_page<-htmlParse(getURL(url=search_url,curl=handle))
##向购物车添加商品是通过HTML表单进行的
###书上原有代码是xpathApply(search_page,"//div[@class='order-box'][position()<2]/form"),
###错,修改
xpathApply(search_page,"//div[@class='row-fixed'][position()<2]/form")
##可以用同一节点的另一属性来定位
提取出书的ID,然后将商品加入购物车
xpath<-"//div[@class='row-fixed'][position()<4]/form/input[@name='bid']/@value"
bids<-unlist(xpathApply(search_page,xpath,as.numeric))
###现在通过向服务器发送必要的信息(bid、add、int)把来自搜索页面的前三个商品加入购物车
###通过curl选项把同一个句柄传递给请求,我们自动把接收到的cookie加到我们的请求里
###cookie类似于参加婚宴的请柬,session类似于参加婚宴的宾客名单
for(i in seq_along(bids)){
    res<-getForm(uri=cart_url,curl=handle,bid=bids[i])
    add=1
    int="keyword_search"
}
###最后我们可以检索购物车并查看已经保存的商品
cart<-htmlParse(getURL(url=cart_url,curl=handle))
clean<-function(x) str_replace_all(xmlValue(x),"(\t)|(\n\n)","")
##书上是cat(xpathSApply(cart,"//div[@class='title-block']",clean))###运行结果为list()
#错,改
xpathSApply(cart,"//div[@class='']/a",xmlValue)###运行结果为NULL

也即往购物车添加商品后并没有商品信息,请问下老师这是什么原因呢?怎么修改呢? 网页源代码为 image

coderLMN commented 7 years ago

你下面的这条 for 循环语句结构有误:

for(i in seq_along(bids)){
    res<-getForm(uri=cart_url,curl=handle,bid=bids[i])
    add=1
    int="keyword_search"
}

这样会导致添加购物车失败,所以购物车里没有内容。书上的代码是

for(i in seq_along(bids)){
    res<-getForm(uri=cart_url,curl=handle,bid=bids[i],add=1,int="keyword_search")
}

改成这条循环代码后,就能添加成功了。

另外,最后那条代码

cat(xpathSApply(cart,"//div[@class='title-block']",clean))

确实出不来结果,原因应该也是网页改版,网页结构变化了。

想看到最新的网页结构,可以把 cart 输出存到一个 cart.html 然后用浏览器打开,就可以发现适用的 XPath 应该是 //div/h3/a

因此,最后一句代码可以改为:

cat(xpathSApply(cart,"//div/h3/a",clean))

这样就可以看到正确结果了。