如何用R(https链接)webscrape安全页面(使用XML包中的readHTMLTable)?

use*_*rJT 18 xml r web-scraping

关于如何使用XML包中的readHTMLTable,我有很好的答案,我使用常规的http页面,但是我无法通过https页面解决我的问题.

我想在这个网站上阅读表格(网址字符串):

library(RTidyHTML)
library(XML)
url <- "https://ned.nih.gov/search/ViewDetails.aspx?NIHID=0010121048"
h = htmlParse(url)
tables <- readHTMLTable(url)
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个错误:文件https://ned.nih.gov/search/Vi...does不存在.

我试图通过https问题(下面的前两行)(使用谷歌找到解决方案)(例如:http://tonybreyal.wordpress.com/2012/01/13/ra-quick-scrape-of -top-grossing-films-from-boxofficemojo-com /).

这个技巧有助于查看更多页面,但任何提取表的尝试都无法正常工作.任何建议表示赞赏 我需要组织,组织标题,经理等表格字段.

 #attempt to get past the https problem 
 raw <- getURL(url, followlocation = TRUE, cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl"))
 head(raw)
[1] "\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; 
...
 h = htmlParse(raw)
Error in htmlParse(raw) : File ...
tables <- readHTMLTable(raw)
Error in htmlParse(doc) : File ...
Run Code Online (Sandbox Code Playgroud)

And*_*rie 26

新软件包httr提供了一个包装器RCurl,可以更容易地抓取各种页面.

不过,这个页面给了我相当多的麻烦.以下工作,但毫无疑问有更简单的方法.

library("httr")
library("XML")

# Define certicificate file
cafile <- system.file("CurlSSL", "cacert.pem", package = "RCurl")

# Read page
page <- GET(
  "https://ned.nih.gov/", 
  path="search/ViewDetails.aspx", 
  query="NIHID=0010121048",
  config(cainfo = cafile)
)

# Use regex to extract the desired table
x <- text_content(page)
tab <- sub('.*(<table class="grid".*?>.*</table>).*', '\\1', x)

# Parse the table
readHTMLTable(tab)
Run Code Online (Sandbox Code Playgroud)

结果:

$ctl00_ContentPlaceHolder_dvPerson
                V1                                      V2
1      Legal Name:                    Dr Francis S Collins
2  Preferred Name:                      Dr Francis Collins
3          E-mail:                 francis.collins@nih.gov
4        Location: BG 1 RM 1261 CENTER DRBETHESDA MD 20814
5       Mail Stop:                                       Â
6           Phone:                            301-496-2433
7             Fax:                                       Â
8              IC:             OD (Office of the Director)
9    Organization:            Office of the Director (HNA)
10 Classification:                                Employee
11            TTY:                                       Â
Run Code Online (Sandbox Code Playgroud)

获取httr此:http://cran.r-project.org/web/packages/httr/index.html


编辑:有关RCurl包的常见问题解答的有用页面:http://www.omegahat.org/RCurl/FAQ.html