【发布时间】: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 <-NULL while(is.null(webElem)){ webElem <- tryCatch({remDr$findElement(using = 'css selector', "node")}, error = function(e){NULL}) } element_next_page <- remDr$findElement(using = 'css selector', "node") element_next_page$sendKeysToElement(list(key="enter"))
标签: r performance rvest rselenium