【发布时间】:2021-06-04 11:38:57
【问题描述】:
我的目标
我正在尝试使用 R 从网页中抓取文本:https://tidesandcurrents.noaa.gov/stationhome.html?id=8467150。出于这个问题的目的,我的目标是访问包含站号的标题文本(“布里奇波特,CT - 站 ID:8467150”)。下面是页面截图。我已经突出显示了我要验证的文本是否存在,并且该文本也在检查元素窗格中突出显示。
我以前的方法是使用readLines() 访问网站的全文。网站最近的更新使文本更难访问,readLines() 不再看到电台名称/号码:
url <- "https://tidesandcurrents.noaa.gov/stationhome.html?id=8467150"
stn <- "8467150"
webpage <- readLines(url, warn = FALSE)
### grep indicates that the station number is not present in the scraped text
grep(x = webpage, pattern = stn, value = TRUE)
可能的解决方案
因此,我正在寻找一种访问目标文本的新方法。我曾尝试使用 httr,但仍然无法将所有 html 文本包含在我从网页中抓取的内容中。 XML 和 rvest 包似乎也很有希望,但我不确定如何识别相关的 CSS 选择器或 XPath 表达式。
### an attempt using httr
hDat <- httr::RETRY("GET", url, times = 10)
txt <- httr::content(hDat, "text")
### grep indicates that the station number is still not present
grep(x = txt, pattern = stn, value = TRUE)
### a partial attempt using XML
h <- xml2::read_html(url)
h2 <- XML::htmlTreeParse(h, useInternalNodes=TRUE, asText = TRUE)
### this may end up working, but I'm not sure how to identify the correct path
html.parse <- XML::xpathApply(h2, path = "div.span8", XML::xmlValue)
无论采用何种方法,我都欢迎任何可以帮助我访问包含电台名称/编号的标题文本的建议。
【问题讨论】:
-
当您查看浏览器的调试页面时,转到 Network 选项卡并重新加载页面,按 Type 排序,点击在第一个“json”条目上,然后查看该查询的响应。您需要的原始数据可能已经封装在 JSON 中,不需要动态页面网页抓取。
-
如果没有找到关联的 JSON,可以使用
RSelenium,如example -
该页面是动态生成的,如果您尝试使用“rnoaa”包或直接访问 API,将会有更好的运气。见api.tidesandcurrents.noaa.gov/api/prod