2017-08-03 222 views
0

使用R和XML包,我使用XML htmlParse函数解析了一个(“HTMLInternalDocument”“HTMLInternalDocument”“XMLInternalDocument”“XMLAbstractDocument”)对象。下面是我感兴趣的xml对象中的行,其中包含两个我希望返回的值。从XML节点解析特定值

除了来自class = gsc_1usr_name(返回“Konrad Wrzecionkowski”)的值之外,我需要将“user =”下的值,在本例中为“QnVgFlYAAAAJ”。我用xpathSApply尝试了几种语法变体,它总是返回NULL。无可否认,当谈到xml时,我非常无知,有什么想法?有没有办法我可以强制这个不同的对象类,如列表,然后在矢量上使用拆分?标准强制(例如,as.list,as.character)似乎不适用于此对象类。

search.page <- "http://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=GVN Powell World Wildlife Fund" 
x <- XML::htmlParse(search.page, encoding="UTF-8") 

它返回一个XML对象,下面是一个单一的条目的子集,选自10. h3 class="gsc_1usr_name行包含值中的每个条目,即我想检索(对于所有10)。

</div> 
</div> 
<div class="gsc_1usr gs_scl"> 
<div class="gsc_1usr_photo"><a href="/citations?user=QnVgFlYAAAAJ&amp;hl=en&amp;oe=ASCII"><img src="/citations?view_op=view_photo&amp;user=QnVgFlYAAAAJ&amp;citpid=3" sizes="(max-width:599px) 75px,(max-width:1251px) 100px, 120px" srcset="/citations?view_op=view_photo&amp;user=QnVgFlYAAAAJ&amp;citpid=3 128w,/citations?view_op=medium_photo&amp;user=QnVgFlYAAAAJ&amp;citpid=3 256w" alt="Konrad Wrzecionkowski"></a></div> 
<div class="gsc_1usr_text"> 
<h3 class="gsc_1usr_name"><a href="/citations?user=QnVgFlYAAAAJ&amp;hl=en&amp;oe=ASCII">Konrad Wrzecionkowski</a></h3> 
<div class="gsc_1usr_aff">Zachodniopomorski Uniwersytet Technologiczny w Szczecinie, Błękitny Patrol <span class="gs_hlt">WWF </span>Polska</div> 
<div class="gsc_1usr_eml">Verified email at <span class="gs_hlt">wwf</span>.pl</div> 
<div class="gsc_1usr_emlb">@wwf.pl</div> 
<div class="gsc_1usr_int"> 
<a class="gsc_co_int" href="/citations?view_op=search_authors&amp;hl=en&amp;oe=ASCII&amp;mauthors=label:ichtiologia_ochrona_przyrody">ichtiologia/ochrona przyrody</a> </div> 
</div> 
</div> 

使用的xpathSApply功能我回来“南越政府鲍威尔”,但也想从用户的值=以下语法。我已经尝试了h3 [@ user ='']的变体,包括类的子查询,但无法获得其他任何内容。

XML::xpathSApply(x, "//h3[@class='gsc_1usr_name']", xmlValue) 

我一直在使用的方法是使用url和readLines。然后我使用strsplit来拉取所需的值。

auth.names <- "Konrad Wrzecionkowski WWF"  
search.page <- paste("http://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=", auth.names, sep="") 

x <- readLines(url(search.page)) 
x <- strsplit(x[[1]], split="user=")[[1]][2] 
x <- strsplit(x, split="&amp;")[[1]][1] 

这里的问题是,谷歌学术搜索似乎并不喜欢的网页抓取和代码定期失败,出现“无法打开连接,HTTP状态为“503 Service Unavailable”错误。但是,这似乎并不是htmlParse的情况。

+0

不幸的是,这个语法不起作用。我在XML中有10个条目,我想要为其检索值。我修改了我的帖子以提供更多关于xml的细节。 –

+0

刮Google是违反他们的ToS。 – hrbrmstr

回答

1
library(rvest) 
library(magrittr) 

url <- "http://scholar.google.com/citations?hl=en&view_op=search_authors&mauthors=GVN Powell World Wildlife Fund" 
xpath = "//*[@id=\"gsc_ccl\"]/div[1]/div[2]/h3/a/span" 

gvn.powell <- url %>% 
    read_html %>% 
    html_nodes(xpath = xpath) %>% 
    html_text 

gvn.powell 
#[1] "GVN Powell"