【问题标题】:R webscraping a slow/overburdened (?) websiteR webscraping一个缓慢/负担过重的(?)网站
【发布时间】:2020-04-13 01:47:19
【问题描述】:

我正在使用 RSelenium、docker 和 rvest 抓取网站以收集用于研究目的的数据。

我已经构建了一个脚本,它会自动“点击”我想要下载内容的页面。 我的问题是,当我运行此脚本时,结果会发生变化。我感兴趣的变量的观察量发生了变化。它涉及大约 50.000 次观察。多次运行脚本时,观察的总数相差几百。

我认为这与互联网连接太慢或网站加载速度不够快有关...或其他...当我更改 Sys.sleep(2) 时,结果也发生了变化,但是如果没有明确的效果,是否将其更改为更高的数字会使情况变得更糟或更好。

在我运行的 R 终端中:

docker run -d -p 4445:4444 selenium/standalone-chrome

然后我的代码看起来像这样:

remDr <- RSelenium::remoteDriver(remoteServerAddr = "localhost",
                             port = 4445L,
                             browserName = "chrome")
remDr$open()
remDr$navigate("url of website")
pages <- 100 # for example, I want information from the first hundred pages
variable <- vector("list", pages)  
i <- 1
while (i <= pages) {
    variable[[i]] <- remDr$getPageSource()[[1]] %>% 
    read_html(encoding = "UTF-8") %>% 
    html_nodes("node that indicates the information I want") %>% # select the information I want
    html_text()
    element_next_page <- remDr$findElement(using = 'css selector', "node that indicates the 'next page button") # select button with which I can go to the next page
    element_next_page$sendKeysToElement(list(key="enter")) # go to the next page
    Sys.sleep(2) # I believe this is done to not overload the website I'm scraping
    i <- i + 1
    }
variable <- unlist(variable)

不知何故,多次运行这会在我取消列出 variable 时保留的观察数量方面不断返回不同的结果。

有人有相同的经验和提示吗?

谢谢。

【问题讨论】:

  • Hi Thissen,也许添加一个检查,看看单击下一步后页面/元素是否更新? UI 中的某些内容通常会发生变化,您可以将其用作验证器。 Sys.sleep() 经常被用来给动态页面渲染时间
  • 您好,Arcoutte,感谢您的评论。我可以使用:remDr$screenshot(display = TRUE) 来查看是否已到达最后一页。但事实上,顺便说一句,我可以看到我的脚本在加载页面时卡住了。也许解决方案是让动态页面有更多时间使用 Sys.sleep() 呈现?
  • 确实如此,但你永远无法确定。也许以下内容可以提供帮助:stackoverflow.com/questions/43402237/…
  • 那么,我会在选择每个节点之前执行此操作吗?我的代码看起来有点像这样? webElem &lt;-NULL while(is.null(webElem)){ webElem &lt;- tryCatch({remDr$findElement(using = 'css selector', "node")}, error = function(e){NULL}) } element_next_page &lt;- remDr$findElement(using = 'css selector', "node") element_next_page$sendKeysToElement(list(key="enter"))

标签: r performance rvest rselenium


【解决方案1】:

您可以考虑在提取文本之前包含以下代码:

for(i in 1 : 100)
{
  print(i)
  remDr$executeScript(paste0("scroll(0, ", i * 2000, ")"))
}

此代码强制应用程序“几乎在网页中的任何地方”运行,这可以帮助页面加载一些未加载的部分。此方法用于以下帖子:How to webscrape texts that are contained into sublinks of a link in R?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2015-08-26
    • 2013-02-12
    • 2020-03-16
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多