问题:网页在 RStudio 中抓取 VIN 号码的品牌/型号/年份

我目前正在做一个项目,我需要找到 VIN 号码的制造商、型号和年份。我有一个包含 300 个不同 VIN 号码的列表。遍历每个单独的 VIN 号码并手动将制造商、型号和年份输入到 Excel 中是非常低效和乏味的。

我曾尝试使用带有 SelectorGadget 的 Rvest 包在 R 中编写几行代码,以便抓取此站点以获取信息,但我没有成功:http://www.vindecoder.net/?vinu003d1G2HX54K724118697&submitu003d解码

这是我的代码:

library("rvest")
Vnum = "1G2HX54K724118697"
site <- paste("http://www.vindecoder.net/?vin=", Vnum,"&submit=Decode",sep="")
htmlpage <- html(site)
VINhtml <- html_nodes(htmlpage, ".odd:nth-child(6) , .even:nth-child(5) , .even:nth-child(7)")
VIN <- html_text(forecasthtml)
paste(forecast, collapse =" ")

当我尝试运行 VINhtml 时,我收到错误消息:list() attr(,"class") [1] "XMLNodeSet"

我不知道我做错了什么。我认为它不起作用,因为它是一个动态网页,但我可能是错的。有没有人对解决这个问题的最佳方法有任何建议?

我也愿意使用其他网站或替代方法来解决这个问题。我只想找到这些 VIN 的型号、制造商和型号年份。任何人都可以帮助我找到一种有效的方法吗?

Here is some sample VINs: YV4SZ592561226129 YV4SZ592371288470 YV4SZ592371257784 YV4CZ982871331598 YV4CZ982581428985 YV4CZ982481423003 YV4CZ982381423543 YV4CZ982171380593 YV4CZ982081460887 YV4CZ852361288222 YV4CZ852281454409 YV4CZ852281454409 YV4CZ852281454409 YV4CZ592861304665 YV4CZ592861267682 YV4CZ592561266859

解答

这是使用RSeleniumrvest的解决方案。

要运行 RSelenium,您必须首先从下载 selenium 服务器,这里是(我的是 2.45 版本)。假设下载的文件在我的文档目录中。然后,在 IDE 中运行RSelenium之前,您必须在 cmd 中运行以下两个步骤。

在 cmd 中输入以下内容: a)cd My Documents# 我在 My Documents 文件夹中安装了 selenium 驱动程序 b) 然后输入:java -jar selenium-server-standalone-2.45.0.jar

library(RSelenium)
library(rvest) 
startServer() 
remDr <- remoteDriver(browserName = 'firefox')
remDr$open()
Vnum<- c("YV4SZ592371288470","1G2HX54K724118697","YV4SZ592371288470")

kk<-lapply(Vnum,function(j){

  remDr$navigate(paste("http://www.vindecoder.net/?vin=",j,"&submit=Decode",sep=""))
  Sys.sleep(30) # this is critical
  test.html <- html(remDr$getPageSource()[[1]]) # this is RSelenium but after this we can use rvest functions until we close the session
  test.text<-test.html%>%
  html_nodes(".odd:nth-child(6) , .even:nth-child(5) , .even:nth-child(7)")%>%
  html_text()
})
kk
[[1]]
[1] "Model: XC70"                          "Type: Multipurpose Passenger Vehicle" "Make: Volvo"                         

[[2]]
[1] "Model: Bonneville"            "Make (Manufacturer): Pontiac" "Model year: 2002"            

[[3]]
[1] "Model: XC70"                          "Type: Multipurpose Passenger Vehicle" "Make: Volvo"   

remDr$close()

附言您可以看到相同的 css 路径不适用于所有 VIN。您必须提前弄清楚(我只是使用了您在问题中提供的路径)。您可以使用某种tryCatch。

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐