【发布时间】:2018-09-25 05:22:47
【问题描述】:
我正在尝试抓取网页
library(RCurl)
webpage <- getURL("https://somewebpage.com")
webpage
<div class='CredibilityFacts'><span id='qZyoLu'><a class='answer_permalink'
action_mousedown='AnswerPermalinkClickthrough' href='/someurl/answer/my_id'
id ='__w2_yeSWotR_link'>
<a class='another_class' action_mousedown='AnswerPermalinkClickthrough'
href='/ignore_url/answer/some_id' id='__w2_ksTVShJ_link'>
<a class='answer_permalink' action_mousedown='AnswerPermalinkClickthrough'
href='/another_url/answer/new_id' id='__w2_ksTVShJ_link'>
class(webpage)
[1] "character"
我正在尝试提取所有 href 值,但前提是它前面带有 answer_permalink 类。
这个的输出应该是
[1] "/someurl/answer/my_id" "/another_url/answer/new_id"
/ignore_url/answer/some_id 应该被忽略,因为它前面是 another_class 而不是 answer_permalink 类。
现在,我正在考虑使用正则表达式的方法。我认为这样的东西可以用于stri_extract_all中的正则表达式
class='answer_permalink'.*href='
但这并不是我想要的。
我可以通过什么方式实现这一目标?此外,除了正则表达式之外,R 中还有一个函数可以像 Javascript 中那样按类提取元素吗?
【问题讨论】:
-
您应该能够使用
rvest包使用类似read_html(webpage) %>% html_nodes("answer_permalink") %>% html_attr("href")的东西来做到这一点 -
@AndrewGustar 返回我
character(0)。