使用 R 从 Planned Parenthood 网站上抓取信息

Use R to Scrape Information from Planned Parenthood Website

我正在尝试使用 rvest 库从计划生育网站上抓取某些信息。我正在查看的网页是here。我目前正在尝试提取网页右侧提供的服务,例如 "abortion services"、"birth control" 等。我在下面有以下代码,它是关闭的吗?

 URL <- "https://www.plannedparenthood.org/health-center/tn"
  Webpage <- read_html(URL)
  all_links <- Webpage %>% 
    html_nodes("p a") %>%
    html_attr('href') %>%
    paste0('https://www.plannedparenthood.org', .)
 URL <- all_links[1]
 Website <- URL
 Webpage <- read_html(URL)
 Services <- Webpage %>% html_nodes("ul li a") %>% html_attr("href")

我从主要的计划生育页面开始,导航到田纳西州的第一个设施。有人可以帮助我获得所提供的服务吗?

这应该可以解决问题:

URL <- "https://www.plannedparenthood.org/health-center/tn"
Webpage <- read_html(URL)
all_links <- Webpage %>% 
  html_nodes("p a") %>%
  html_attr('href') %>%
  paste0('https://www.plannedparenthood.org', .)
URL <- all_links[1]
Website <- URL
Webpage <- read_html(URL)
Services <- Webpage %>% html_nodes(".services a") %>% html_text()

给出:

> Services
[1] "Abortion Services"                            "Birth Control"                                "HIV Testing"                                  "LGBTQ Services"                              
[5] "Men's Health Care"                            "Morning-After Pill (Emergency Contraception)" "Pregnancy Testing & Services"                 "STD Testing, Treatment & Vaccines"           
[9] "Women's Health Care" 

我只在最后一行更改了这个%>% html_nodes(".services a") %>% html_text()

所以我使用了一个更具体的 css 选择器,然后只使用了这个选择器产生的 html 文本。

如果您不熟悉 CSS,请尝试 this Google Chrome 插件,这使得获得正确的 CSS 选择器更加容易。