【问题标题】:Scraping ajax sites with r使用 r 抓取 ajax 站点
【发布时间】:2020-03-25 23:07:51
【问题描述】:

有人知道我是否可以用 httr 和 rvest 刮掉这个 sitethis one,还是应该使用 selenium 或 phantomjs?

这两个网站似乎都在使用 ajax,我似乎无法通过它。

基本上我所追求的是以下内容:

# I want this to return the titles of the listings, but I get character(0)
"https://www.sahibinden.com/satilik" %>% 
  read_html() %>% 
  html_nodes(".searchResultsItem .classifiedTitle") %>% 
  html_text() 

# I want this to return the prices of the listings, but I get 503
"https://www.hurriyetemlak.com/konut" %>% 
  read_html() %>% 
  html_nodes(".listing-item .list-view-price") %>% 
  html_text()

欢迎任何关于 v8 或人工会话的想法。

此外,也欢迎任何纯粹的 curl 解决方案。稍后我会尝试将它们翻译成 httr :)

谢谢

【问题讨论】:

  • 你想要的输出是什么?尽量准确 - 例如:“Referanz Ankara 199.000 TL”
  • @TonioLiebrand 我已经更新了问题

标签: r web-scraping rvest httr rselenium


【解决方案1】:

您必须设置 cookie 才能成功发出请求。

应检查网站 (sahbinden) 是否允许抓取。

  • robotstxt::paths_allowed(paths = "https://www.sahibinden.com/satilik", warn = FALSE) --> robotstxt 好像没有禁止
  • 如果您在浏览器中删除 cookie 后更新网站,则该网站不再允许访问并报告异常行为 --> 指示针对抓取的反措施
  • 请务必阅读使用条款。

因此,我将共享“理论”代码,但不共享所需的 cookie 数据,这取决于用户。

完整代码如下:

library(xml2)
library(httr)
library(magrittr)
library(DT)
url <- "https://www.sahibinden.com/satilik"

YOUR_COOKIE_DATA <- NULL
if(is.null(YOUR_COOKIE_DATA)){
  stop("You did not set your cookie data. 
        Also please check if terms of usage allow the scraping.")
}
response <- url %>% GET(add_headers(.headers = c(Cookie = YOUR_COOKIE_DATA))) %>%
            content(type = "text", encoding = "UTF-8")
xpathes <- data.frame(
    XPath0 = 'td[2]',
    XPath1 = 'td[3]/a[1]',
    XPath2 = 'td/span[1]',
    XPath3 = 'td/span[2]',
    XPath4 = 'td[4]',
    XPath5 = 'td[5]',
    XPath6 = 'td[6]',
    XPath7 = 'td[7]',
    XPath8 = 'td[8]'
)

nodes <- response %>% read_html %>% html_nodes(xpath = 
"/html/body/div/div/form/div/div/table/tbody/tr"
)

output <- lapply(xpathes, function(xpath){
    lapply(nodes, function(node) html_nodes(x = node, xpath = xpath) %>% 
    {ifelse(length(.), yes = html_text(.), no = NA)}) %>% unlist
})
output %>% data.frame %>% DT::datatable()

关于抓取网站数据的权利。我尝试关注:Should questions that violate API Terms of Service be flagged?。虽然,在这种情况下,它的“潜在违规行为”。

以编程方式读取 cookie:

我不确定是否可以使用浏览器完全跳过:

【讨论】:

  • 感谢您的回答。但是,问题的本质是如何让数据完全保留在 R 中,那么如何在有或没有达到 ajax 端点的情况下获得所需的 cookie 数据。 GET("https://www.sahibinden.com/satilik") %&gt;% cookies() 不返回要使用的 cookie,并且不能从浏览器复制粘贴 cookie,最好使用无头的。此外,您提出有关抓取网站的担忧是完全正确的,但是,这些网站是我无法使用 rvest 抓取的网站的示例,所以我想知道我是否遗漏了某事。我不打算刮掉它们
  • 关于 cookie。如果您想要一个通用的答案:我不确定是否可以完全跳过使用浏览器,请参阅上面的编辑。
猜你喜欢
  • 2018-12-23
  • 2016-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
相关资源
最近更新 更多