【问题标题】:rvest returning NA投资回报 NA
【发布时间】:2018-02-08 13:50:36
【问题描述】:

我正在使用“rvest”进行网页抓取,但我无法从页面中提取模型的价格:- https://www.motorola.com/us/products/moto-z-force-droid-edition .我需要从页面中提取“$720.00”。我的代码是:-

library(rvest)

data<-read_html("https://www.motorola.com/us/products/moto-z-force-droid-edition")

price<-data%>%
html_nodes(".price-amount")%>%
html_text()
print(price)

我不断得到字符(0)的价格。

请帮忙。

【问题讨论】:

  • 该站点使用 javascript 呈现页面(并将价格插入页面)。要查看 rvest 下载做什么 download.file("&lt;yoururl&gt;", "output.html") 并在编辑器中查看 output.html。你会看到价格不见了;有一些占位符&lt;span&gt;s 填满了价格。为了抓取这样的网站,您必须使用无头浏览器,例如 PhantomJS。也许r-bloggers.com/web-scraping-javascript-rendered-sites 有用。
  • 谢谢。你能举个例子吗?
  • 我对 PhantomJS 没有任何经验,所以我无法帮助你(这也是我没有写答案的原因)。对不起。
  • 没问题。谢谢。
  • 搜索一些关于使用RSelenium的教程,这是phantomJS(和其他浏览器)的一种可能接口。

标签: r rvest


【解决方案1】:
url<-"https://www.motorola.com/us/js/motorola_blc_catalog/price/1281"
page<-html_session(url)
text<-XML::xmlToList(XML::xmlParse(httr::content(page$response)$price))
price<-text$tbody$tr$td$span$text

【讨论】:

    【解决方案2】:

    将 rvest 与 RSelenium 和 seleniumPipes 一起使用。确保下载 phantomJS 并将 .exe 文件放在当前 R 工作目录中。详情请见my other answser

    library(tidyverse)
    library(rvest)
    library(RSelenium) # start a server with utility function
    library(seleniumPipes)
    #start server
    rD <- rsDriver (browser = 'chrome',chromever = "latest",port = 4445L)
    #open browser
    remDr <- remoteDr(browserName = "chrome",port = 4445L)
    web_url <- "https://www.motorola.com/us/products/moto-z-force-droid-edition"
    
    remDr %>% go(web_url)
    price <- remDr %>% getPageSource() %>% html_nodes(".price-amount") %>% html_text()
    
    print(price)    
    [1] "$30.00/mo" "$720.00"   "$720.00" 
    
    remDr %>% deleteSession() # delete session
    rD[["server"]]$stop() # close server
    

    简而言之,您需要使用无头浏览器来呈现 javascript 生成的值。之后,您可以照常使用 rvest。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 2020-09-27
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      相关资源
      最近更新 更多