如何使用 R 抓取点击信息?

How to web-scrape on-click information with R?

我正在尝试从该网站抓取 phone 号码:http://olx.pl/oferta/pokoj-1-os-bielany-encyklopedyczna-CID3-IDdX6wf.html#c1c0e14c53. The phone number can be scraped with rvest package with selector .\'id_raw\'\::nth-child(1) span+ div strong (suggested by [selectorGadget] http://selectorgadget.com/)。

问题是点击掩码后可以获取到信息。所以我必须以某种方式打开一个会话,提供点击然后抓取信息。

编辑 顺便说一句,这不是 link 恕我直言。看看源代码。我有一个问题,因为我是普通的 R 用户,而不是 javascript 程序员。

这是一个使用 RSelenium, (RSelenium introduction) 和 phantomjs 的解决方案。

但是,我不确定它的可用性如何,因为它在我的机器上运行速度非常慢,而且我不是 phantomjs 或 selenium 专家,所以我不知道速度改进在哪里尚未完成,所以需要研究一下...

编辑

我又试了一次,速度似乎还可以。

library(RSelenium)
library(rvest)

## Terminal command to start selenium (on ubuntu)
## cd ~/selenium && java -jar selenium-server-standalone-2.48.2.jar
url <- "http://olx.pl/oferta/pokoj-1-os-bielany-encyklopedyczna-CID3-IDdX6wf.html#c1c0e14c53"

RSelenium::startServer()
remDr <- remoteDriver(browserName = "phantomjs")

remDr$open()
remDr$navigate(url)

# css <- ".cpointer:nth-child(1)"  ## couldn't get this to work
xp <- "//div[@class='contactbox-indent rel brkword']"
webElem <- remDr$findElement(using = 'xpath', xp)

# webElem <- remDr$findElement(using = 'css selector', css)
webElem$clickElement()

## the page source now includes the clicked element
page_source <- remDr$getPageSource()[[1]]
pos <- regexpr('class=\"xx-large', page_source)

## you could write a more intelligent regex, but this works for now
phone_number <- substr(page_source, pos + 11, pos + 21)
phone_number
# "503 155 744"

# remDr$close()
# remDr$closeServer()

您可以获取嵌入在 <li> 标记中的数据,这些数据告诉 onclick 处理程序要做什么,然后直接获取数据:

library(httr)
library(rvest)
library(purrr)
library(stringr)

URL <- "http://olx.pl/oferta/pokoj-1-os-bielany-encyklopedyczna-CID3-IDdX6wf.html#c1c0e14c53"

pg <- read_html(URL)

html_nodes(pg, "li.rel") %>%       # get the 'special' <li> tags
  html_attrs() %>%                 # extract all the attrs (they're non-standard)
  flatten_chr() %>%                # list to character vector
  keep(~grepl("rel \{", .x)) %>%  # only want ones with 'hidden' secret data
  str_extract("(\{.*\})") %>%    # only get the data
  unique() %>%                     # there are duplicates
  map_df(function(x) {

    path <- str_match(x, "'path':'([[:alnum:]]+)'")[,2]                  # extract out the path
    id <- str_match(x, "'id':'([[:alnum:]]+)'")[,2]                      # extract out the id

    ajax <- sprintf("http://olx.pl/ajax/misc/contact/%s/%s/", path, id)  # make the AJAX/XHR URL
    value <- content(GET(ajax))$value                                    # get the data

    data.frame(path=path, id=id, value=value, stringsAsFactors=FALSE)    # make a data frame

  }) 

## Source: local data frame [3 x 3]
## 
##           path    id       value
##          (chr) (chr)       (chr)
## 1        phone dX6wf 503 155 744
## 2        skype dX6wf    e.bobruk
## 3 communicator dX6wf     7686136

完成所有这些后,我对网站没有更好的 Service/Use 条款感到非常失望。很明显,他们真的不想让你抓取这些数据。