需要对汽车之间里某个车型论坛的评论进行爬虫,我需要抓取楼主、每层楼的评论、日期、层主是否为认证车主,然后write.table,但是我看不懂HTML语句,不知道一些代码该怎样转换为R语言,特别是红色字体部分,求解救!PS:以下的代码是我在别人对其他抓取其他网站的基础上改编过来的
library(RCurl)
library(bitops)
library(XML)
library(reshape)
#读取
start_url = "http://club.autohome.com.cn/bbs/thread-c-3126-29386112-1.html"
#构造请求头
cust_header =c("User-Agent"="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0",
"Accept"="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language"="en-us",
"Connection"="keep-alive")
#读取PageSouce
pagesource <- getURL(start_url,httpheader=cust_header,.encoding="utf-8")
#解析页数
parseTotalPage <- function(pagesource){
doc <- htmlParse(pagesource)
as.numeric(sapply(getNodeSet(doc, '//div[@class="page"]/a[last()-1]/text()'), xmlValue))
}
#解析页面内容,获取门店名称、描述、优惠价,门店价
parseContent <- function(pagesource){
doc <- htmlParse(pagesource)
x1<-sapply(getNodeSet(doc, '//div[@class="maxtitle"]//text()'), xmlValue) #499编码所在行数
x2<-sapply(getNodeSet(doc, '//div[@class="w740"]//text()'), xmlValue) #508
y<-data.frame(x1,x2)
}
#获取总页数和第一页内容
total_page <- parseTotalPage(pagesource)
pageresults <- parseContent(pagesource)
#生成2-n页url
page = 1:(total_page -1)
url_list = ""
url_list[page] = paste0("http://club.autohome.com.cn/bbs/thread-c-3126-29386112-1.html",page +1)
#循环读取url,并进行下载解析
for (url in url_list){
pagesource <- getURL(url,httpheader=cust_header,.encoding="utf-8")
pageresult <- parseContent(pagesource)
pageresults <- rbind(pageresults,pageresult)
}
pageresults
#输出结果到文件
write.table(pageresults,"result.txt",row.names=FALSE)