问题描述
library(RSelenium)
library(dplyr)
library(rvest)
rD<-rsDriver(browser = 'firefox',port = 4875L)
remDr<-rD$client
input_galaxus<-c('https://www.galaxus.ch/8606656','https://www.galaxus.ch/9796481','https://www.galaxus.ch/10592688')
vec_galaxus<-vector()
i=0
for (j in input_galaxus){
remDr$navigate(j)
i=i+1
try(vec_galaxus[i]<-read_html(remDr$getPageSource()[[1]])%>%
html_nodes('div strong')%>%
html_text()%>%
nth(5))
Sys.sleep(runif(1,min=5,max=10))
}
但是当循环转到第二个网页时,它无法再访问该网站。
有人能帮我解决这个问题吗?
非常感谢!
解决方法
我让它与 rvest
会话一起工作 - 不需要 Selenium。只需删除 RSelenium 行并将您的 for
循环替换为
sess <- session(input_galaxus[1]) #to start the session
for (j in input_galaxus){
sess <- sess %>% session_jump_to(j) #jump to URL
i=i+1
try(vec_galaxus[i] <- read_html(sess) %>% #can read direct from sess
html_nodes('div strong') %>%
html_text() %>%
nth(5))
Sys.sleep(runif(1,min=5,max=10))
}
vec_galaxus
[1] " 399.–" " 660.–" " 931.–"