css - 从R中的链接中提取标题

标签 css r substring rvest

我正在使用 R 中的 rvest 包练习网络抓取。到目前为止,该页面是一个很好的指南。 (http://zevross.com/blog/2015/05/19/scrape-website-data-with-the-new-r-package-rvest/)。使用工具选择器小工具,我可以识别我想要的元素的类或 div 元素引用(据我所知)。

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

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

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 函数来获取另一个元素吗?我觉得我很接近!

感谢您的帮助。

最佳答案

名称有两个来源。标题属性和文本。它们的格式可能略有不同,或者其中一个可能包含中间名缩写或其他任何内容。使用您最喜欢的那个。

html_attr(fnames, "标题")

html_text(fnames)

关于css - 从R中的链接中提取标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37687435/

相关文章:

html - 使这个 SVG 全宽

html - 如何将搜索按钮对齐到搜索框的右侧

r - 根据另一列 r 的值在列之间切换元素

substring - 复杂的 T-SQL 子字符串

javascript - 根据当前屏幕窗口大小为我的模态窗口设置最大高度

Jquery .css ("background-image") 不执行任何操作

r - 使用 R 代码精确列出给定包导入的包?

r - 如何拆分不同列表中的非连续数字

java - .NET与Java子串操作性能对比

algorithm - Knuth-Morris-Pratt 算法中的前缀函数计算