2016-06-07 63 views
3

我正在使用R中的rvest软件包来练习网络抓取。到目前为止,该页面已经是一个很好的指南。 (http://zevross.com/blog/2015/05/19/scrape-website-data-with-the-new-r-package-rvest/)。使用工具Selector Gadget我可以识别我想要的项目的类或div元素引用(据我所知)。从R中链接中提取标题

所以我刚去维基百科,并试图提取美国总统名单。该页面的链接是https://en.wikipedia.org/wiki/List_of_Presidents_of_the_United_States。 Selector Gadget告诉我元素类/ div /? (不知道该怎么称呼它)是“大”。

这里是我到目前为止的代码:

site = read_html("https://en.wikipedia.org/wiki/List_of_Presidents_of_the_United_States") 
fnames = html_nodes(site,"big a") 

和部分输出为:

{xml_nodeset (44)} 
[1] <a href="/wiki/George_Washington" title="George Washington">George Washington</a> 
[2] <a href="/wiki/John_Adams" title="John Adams">John Adams</a> 
[3] <a href="/wiki/Thomas_Jefferson" title="Thomas Jefferson">Thomas Jefferson</a> 
[4] <a href="/wiki/James_Madison" title="James Madison">James Madison</a> 
[5] <a href="/wiki/James_Monroe" title="James Monroe">James Monroe</a> 
[6] <a href="/wiki/John_Quincy_Adams" title="John Quincy Adams">John Quincy Adams</a> 
[7] <a href="/wiki/Andrew_Jackson" title="Andrew Jackson">Andrew Jackson</a> 
[8] <a href="/wiki/Martin_Van_Buren" title="Martin Van Buren">Martin Van Buren</a> 

太好了!所以我已经提取了链接的名字!我只是想要名字,所以我不知道如何在这里继续。有没有办法轻松获取链接html代码之间的名称?或者我应该使用html_nodes函数来获取另一个元素吗?我觉得我很接近!

谢谢你的帮助。

+1

HTML_TEXT'(fnames)'应该这样做。 – cory

+0

头脑被炸毁。这工作!非常感谢!!! – user137698

+0

或...'html_attr(fnames,“title”)' – cory

回答

2

名称有两个来源。标题属性和文本。它们的格式可能稍有不同,或者可能包含中间首字母或其他。使用你最喜欢的那个。

html_attr(fnames, "title")

OR

html_text(fnames)