Re: [分享] 更进一步使用RSelenium抓取PTT内容与通知

楼主: celestialgod (天)   2016-07-24 17:56:52
※ 引述《wanson (望生)》之铭言:
: 最近看到有人教学使用RSelenium 抓取PTT的内容
: https://www.youtube.com/watch?v=PYy5C9IIgp8
: 我自学了一下发现的确可行
: 我自己本身因为有搭共乘的需求
: 特别搭乘的是比较少人提供的部分
: 所以我想更进一步使用这个方法并且进一步通知
: 上述网址的教学只能将爬到的档案存成一个file
: 并且限制在该网页的首页
: 但是我希望更多的功能为以下,想要请问一下不知道可否使用R更进一步处理
: 1. 爬取更多页面或是该版所有的页面
: 这个部分我发现
: 他似乎根据网址的index那边变动
: 如果我使用最旧就会等于1,下一页就是二
: 但我使用最新他只会显示index
: https://www.ptt.cc/bbs/car-pool/index2.html
: 似乎可以写回圈去提取
: 2. 定期自动爬虫
: 我想要让电脑设定每两小时爬一次,不知道要怎样设定
: 不知道是否可以教学一下
: 谢谢
: 以下是使用他的教学我产生的code
: library(RSelenium)
: url= "https://www.ptt.cc/bbs/car-pool/index.html"
: remDr <- remoteDriver(remoteServerAddr = "localhost"
: , port = 4444
: , browserName ="firefox"
: )
: remDr$open() #open browser
: remDr$getStatus()#check the status of browser
: remDr$navigate(url)# website to crawl
: #the separate symbol in ppt is r-ent
: #get the element from the website
: webElem<-remDr$findElements('css selector', ".r-ent")#class for period (.) id
: then use #
: a = sapply(webElem, function(x){
: c =x$findChildElement('css selector', '.author')
: d =x$findChildElement('css selector', '.title')
: e =x$findChildElement('css selector', '.date')
: cbind(c("author" = c$getElementText(), "title" =
: d$getElementText(),e$getElementText()))
: }
: )
: t=as.data.frame(t(a))
第一个问题的话就是抓上一页的按钮连结,然后再慢慢往前转就好,下面举例
RSelenium是满好入手的工具
抓到感觉后就可以慢慢开始用httr, xml2去抓网页,速度会相对快很多
举例如下:
(stri_conv只用在windows系统,linux/mac可以不需要)
library(httr)
library(xml2)
library(pipeR)
library(stringi)
library(stringr)
# url
url <- "https://www.ptt.cc/bbs/car-pool/index.html"
# parse网页
html_nodex <- GET(url) %>>% content
# 找转页数的按钮
btnPageChange <- html_nodex %>>% xml_find_all("//div/a[@class='btn wide']")
# 找上一页按钮的位置
locPrevPage <- btnPageChange %>>% xml_text %>>%
stri_conv("UTF8", "BIG5") %>% str_detect("上页")
# 看上一页的index编号
indexCount <- btnPageChange[locPrevPage] %>>% xml_attr("href") %>>%
str_match("index(\\d{4})") %>>% `[`(2) %>>% as.integer
# 要抓的字段资讯
infoVec <- c(title = "//div[@class='title']",
date = "//div[@class='date']",
author = "//div[@class='author']")
# 先抓第一页的
info <- sapply(infoVec, function(xpath){
xml_find_all(html_nodex, xpath) %>>% xml_text %>>%
stri_conv("UTF8", "BIG5") %>>% str_replace_all("\t|\n| ", "")
})
# 把前天的日期抓出来 (只要date出现前天,就停止,
# 当然有可能置底是前天发的就GG了,这个再自己修改)
crawlDate <- format(Sys.Date()-2, "%m/%d") %>>%
str_extract("[1-9]{1,2}/\\d{2}")
while (continueCrawl)
{
# 把index.html改成上一页/上上一页/...
html_nodex <- url %>>%
str_replace("index.html", sprintf("index%i.html", indexCount)) %>>%
GET %>>% content
# 抓出那一页的资讯
tmpInfo <- sapply(infoVec, function(xpath){
xml_find_all(html_nodex, xpath) %>>% xml_text %>>%
stri_conv("UTF8", "BIG5") %>>% str_replace_all("\t|\n| ", "")
})
# 跟之前的合并
info <- rbind(info, tmpInfo)
# 如果出现不是昨天日期的就停止
if (any(tmpInfo[ , "date"] == crawlDate))
continueCrawl <- FALSE
indexCount <- indexCount - 1
}
info # 即为所求
每两小时执行一次的话,就外面加一层while (TRUE)然后搭配Sys.sleep使用

Links booklink

Contact Us: admin [ a t ] ucptt.com