【问题标题】:R extract text from webpage using rvestR使用rvest从网页中提取文本
【发布时间】:2021-04-19 15:38:55
【问题描述】:

我正在尝试从网页中提取两段文本

网页

page <- read_html("https://www.decathlon.fr/p/kettlebell-12kg/_/R-p-152874")

以及我要提取的部分文本的 html 源代码

<p class="ab-info-stock__text ab-test-info-red">Rupture de stock sur cette taille</p>

我尝试使用rvest 提取它,但它似乎不起作用

library(rvest)
element = page %>% html_nodes("ab-info-stock__text ab-test-info-red")

非常感谢一些关于我哪里出错的帮助。

【问题讨论】:

    标签: r rvest


    【解决方案1】:

    该网站似乎是动态加载的。因此,您应该使用RSelenium 而不是仅仅使用rvest 来访问该页面。

    以下代码适用于我:

    rD <- RSelenium::rsDriver(browser="firefox")
    remDr <- rD[["client"]]
    remDr$navigate("https://www.decathlon.fr/p/kettlebell-12kg/_/R-p-152874")
    
    # scroll down a bit and wait some seconds just to ensure the loading of the page
    remDr$executeScript(paste("scroll(0,",i*10000,");")) 
    Sys.sleep(5)
    
    # fetch the html code
    webpage<- remDr$getPageSource()
    webpage<- xml2::read_html(webpage[[1]])
    
    # obtain the text --- use "library(dplyr)" in case you haven't loaded it yet for the pipe (%>%)
    stocktext <- webpage %>%
      rvest::html_nodes(".ab-info-stock__text.ab-test-info-red") %>% 
      rvest::html_text()
    
    # exit
    remDr$close()
    gc()
    rD$server$stop()
    system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)
    

    【讨论】:

    • Varun,我刚刚试了一下,它确实有效。 -- 你得到什么错误信息?无论如何,我编辑了帖子以使代码更加一致。请确保至少加载库dplyr 以使用管道(%&gt;%);并确保安装RSelenium 包;最后,使用您需要的浏览器(现在,正如您在第 1 行中看到的,它显示 browser="firefox" 这是我的默认浏览器)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2015-09-06
    相关资源
    最近更新 更多