我目前正在尝试从特定网站 ( http://www.faunaeur.org/?no_redirect=1 ) 抓取生物多样性数据。我已经设法获得了一些结果,但没有像我希望的那样自动化......第一部分已完成,正在浏览网站:
设置 Rselenium:
library(RSelenium)
download.file("https://github.com/mozilla/geckodriver/releases/download/v0.11.1/geckodriver-v0.11.1-win64.zip",destfile="./gecko.zip")
unzip("./gecko.zip",exdir=".",overwrite=T)
checkForServer(update=T)
selfserv = startServer()
mybrowser1 = remoteDriver(browserName="firefox",extraCapabilities = list(marionette = TRUE))
mybrowser1$open()
然后开始浏览(以巴利阿里群岛为例):
mybrowser1$navigate("http://www.faunaeur.org/distribution.php?current_form=species_list")
mybrowser1$findElement(using="xpath","//select[@name='taxon_rank']/option[@value='7']")$clickElement() # Class
mybrowser1$findElement(using="xpath","//input[@name='taxon_name']")$sendKeysToElement(list('Oligochaeta')) # Oligochète
mybrowser1$findElement(using="xpath","//select[@name='region']/option[@value='15']")$clickElement()
mybrowser1$findElement(using="xpath","//input[@name='include_doubtful_presence']")$clickElement()
mybrowser1$findElement(using="xpath","//input[@name='submit2']")$clickElement()
从现在起,我可以使用以下方法下载 20 个亚种的 xls 文件:
mybrowser1$findElement(using = "xpath", "//a[@href='JavaScript:document.export_species_list.submit()']")$clickElement()
但这不是我想要的,我不想使用“点击”。是否可以直接在我的 R 环境中从此 JavaScript 链接下载文件,或者使用 Rselenium 直接从网页的源代码中抓取 20 个亚种的表格?
我尝试了这两种解决方案,但陷入了僵局...最大的问题是该页面是临时页面或“结果页面”,而且似乎我在其中找不到任何@value,@id,@与我需要的表对应的名称或@class。
有关解决方案的任何线索都意味着通过 R 实现自动化的方式吗?我需要这种形式,因为脚本必须由需要自己创建结果的人运行。提前致谢 !
最佳答案
如果您只想在网站上显示表格,则可以通过 httr
在没有 Rselenium 的情况下完成,如下所示:
require(rvest)
require(httr)
res <- POST("http://www.faunaeur.org/species_list.php",
encode = "form",
body = list(selected_regions="15",
show_what="species list",
referring_page="distribution",
taxon_rank="7",
taxon_name="Oligochaeta",
region="15",
include_doubtful_presence="yes",
submit2="Display Species",
show_what="species list",
species_or_higher_taxa="species"))
doc <- res %>% read_html
dat <- doc %>% html_table(fill=TRUE, ) %>% .[[9]]
colnames(dat) <- dat[1,]
dat <- dat[-1, ]
这给你:
Family Species / subspecies
2 Acanthodrilidae Microscolex dubius (Fletscher 1887)
3 Enchytraeidae Enchytraeus buchholzi Vejdovsky 1878
4 Enchytraeidae Fridericia berninii Dozsa-Farkas 1988
5 Enchytraeidae Fridericia caprensis Bell 1947
...
21 Naididae Aulophorus furcatus (Oken 1815)
关于Rselenium - 如何从没有 id 或任何类型名称的网页中抓取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41489987/