2014-02-26 126 views
2

我正在使用R来刮取一些网页。其中一页是重定向到新页面。当我用readLines本页面像这样如何在读取R行之前等待网页加载?

test <- readLines('http://zfin.org/cgi-bin/webdriver?MIval=aa-markerselect.apg&marker_type=GENE&query_results=t&input_name=anxa5b&compare=contains&WINSIZE=25') 

我得到的还是重定向页面,而不是http://zfin.org/ZDB-GENE-030131-9076最后一页。我想使用这个重定向页面,因为在它的URL中有input_name=anxa,这可以很容易地抓取不同输入名称的页面。

如何获取最终页面的HTML?


重定向页面:http://zfin.org/cgi-bin/webdriver?MIval=aa-markerselect.apg&marker_type=GENE&query_results=t&input_name=anxa5b&compare=contains&WINSIZE=25

最后一页:http://zfin.org/ZDB-GENE-030131-9076

回答

2

我不知道如何重定向之前,直到重定向,但在网页的源代码等等,你可以看到(在脚本标记中)一个包含重定向路径的JavaScript函数replaceLocationreplaceLocation(\"/ZDB-GENE-030131-9076\")

然后我建议你解析代码并得到这个路径。 这里是我的解决方案:

library(RCurl) 
library(XML) 

url <- "http://zfin.org/cgi-bin/webdriver?MIval=aa-markerselect.apg&marker_type=GENE&query_results=t&input_name=anxa5b&compare=contains&WINSIZE=25" 

domain <- "http://zfin.org" 

doc <- htmlParse(getURL(url, useragent='R')) 

scripts <- xpathSApply(doc, "//script", xmlValue) 

script <- scripts[which(lapply(lapply(scripts, grep, pattern = "replaceLocation\\([^url]"), length) > 0)] 

# > script 
# [1] "\n   \n\t \n\t  replaceLocation(\"/ZDB-GENE-030131-9076\")\n   \n   \n\t" 

new.url <- paste0(domain, gsub('.*\\"(.*)\\".*', '\\1', script)) 

readLines(new.url) 

xpathSApply(doc, "//script", xmlValue)得到源代码中的所有脚本。

script <- scripts[which(lapply(lapply(scripts, grep, pattern = "replaceLocation\\([^url]"), length) > 0)]获取包含带重定向路径的函数的脚本。

"replaceLocation\\([^url]"你需要排除的“URL”的原因在两个replaceLocation功能,一个与对象的URL,另一个与评估对象(串))

而且finaly gsub('.*\\"(.*)\\".*', '\\1', script)只得到你需要在脚本中,函数的参数,路径。

希望得到这个帮助!

相关问题