-
Notifications
You must be signed in to change notification settings - Fork 10
Open
Description
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="[email protected]",
'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)###运行结果为NULLMetadata
Metadata
Assignees
Labels
No labels
