我正在尝试爬取一个网页
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 中按 class 提取元素的函数?
rvest
包来完成这个任务,类似于read_html(webpage) %>% html_nodes("answer_permalink") %>% html_attr("href")
。 - Andrew Gustarcharacter(0)
。 - Ronak Shah