rad*_*906 4 r vin web-scraping rstudio rvest
我目前正在开展一个项目,我需要找到VIN编号的制造商,型号和年份.我列出了300个不同的VIN号码.通过每个单独的VIN编号并手动将制造商,型号和年份输入excel是非常低效和乏味的.
我已经尝试使用带有SelectorGadget的Rvest包在R中编写几行代码以便抓取这个站点来获取信息但是我没有成功:http://www.vindecoder.net/? edit = 1G2HX54K724118697&subsmit = Decode
这是我的代码:
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 =" ")
Run Code Online (Sandbox Code Playgroud)
当我尝试运行VINhtml时,我收到错误消息:list()attr(,"class")[1]"XMLNodeSet"
我不知道我做错了什么.我认为它不起作用,因为它是一个动态的网页,但我可能是错的.有没有人对解决这个问题的最佳方法有任何建议?
我也愿意使用其他网站或其他方法来解决这个问题.我只是想找到这些VIN的型号,制造商和型号年份.有谁能帮我找到一个有效的方法吗?
下面是一些示例的VIN:YV4SZ592561226129 YV4SZ592371288470 YV4SZ592371257784 YV4CZ982871331598 YV4CZ982581428985 YV4CZ982481423003 YV4CZ982381423543 YV4CZ982171380593 YV4CZ982081460887 YV4CZ852361288222 YV4CZ852281454409 YV4CZ852281454409 YV4CZ852281454409 YV4CZ592861304665 YV4CZ592861267682 YV4CZ592561266859
这是使用RSelenium和的解决方案rvest.
要运行RSelenium,你必须先从这里下载selenium服务器(我的是2.45版).假设下载的文件位于My Documents目录中.然后,RSelenium在IDE中运行之前,必须在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()
Run Code Online (Sandbox Code Playgroud)
PS您可以看到相同的css路径不适用于所有VIN.你必须提前弄清楚(我只是使用了你在问题中提供的路径).你可以使用某种tryCatch.