我正在一个网站上执行网页垃圾处理,已经能够获得基本数据,但我现在需要从页面更复杂的部分收集数据.

我正在使用rvest从AAA天然气价格网站上获取数据:

https://gasprices.aaa.com/

我现在正在try 提取县级数据,该数据仅显示在 map 上(如果您将光标悬停在单个县上.我需要获取不同州各个县的县天然气价格.例如,如果您单击缅因州,转到缅因州页面(https://gasprices.aaa.com/?state=ME),我需要在网上浏览Aroostook( map 上最北端的县)的价格.

我已经能够使用rvest提取地铁区域的数据(页面下方),使用html_nodes和 node "td".然而, map 的代码更复杂.而不是简单的"td" node ,开发者工具(在Chrome中)给出了<td class="fm-tooltip-comment">$4.928</td的价格(4.928美元是Aroostok中截至本文发布日期的当前价格).我似乎无法用rvest包来提取它.

我已经读到该类可以使用,或者其他人建议在rvest中使用css代码来指定它,但我不知道如何这样做.提取地铁区域的数字很简单,但是 map 中嵌入的县级价格似乎并不容易获取.

有没有办法提取县级数据,这样我就可以在R中浏览网页了?那么,我必须从中 Select 的所有县/州都可以重复吗?我需要css代码吗?如果需要,我如何正确访问/编写它以供rvest使用?

推荐答案

It looks like the information you are looking for is store in the "index.php" file that gets downloaded when the web page loads. The current link for Maine is "https://gasprices.aaa.com/index.php?premiumhtml5map_js_data=true&map_id=21&r=89346&ver=5.9.3".
I am not sure what the r=89346 value is for, maybe a timestamp, tracking id, temporary token (to prevent web scraping) etc. I suspect this URL will change thus you may need to use the developer tools on the browser to obtain the current url.
Also, map_id refers to state but I don't know the rational, Florida is 1, NC is 35 and Maine is 21.

Download this file, then extract the JSON data and convert.

library(dplyr)

#read the index_php file and turn it into character string
index_php <-readLines("https://gasprices.aaa.com/index.php?premiumhtml5map_js_data=true&map_id=21&r=19770&ver=5.9.3")
index_php <- paste(index_php, collapse = " ")

#extract out the correct JSON data part and convert
jsondata <- stringr::str_extract(index_php, "\\{\"st1\":.+?\\}\\}") 
data<-jsonlite::fromJSON(jsondata)

#create a data frame with the results
answer <- bind_rows(data)

      id name         shortname link  comment image color_map color_map_over
   <int> <chr>        <chr>     <chr> <chr>   <chr> <chr>     <chr>         
 1     1 Androscoggin ""        ""    $4.964  ""    #ca3338   #ca3338       
 2     2 Aroostook    ""        ""    $4.928  ""    #dd7a7a   #dd7a7a       
 3     3 Cumberland   ""        ""    $4.944  ""    #ca3338   #ca3338       
 4     4 Franklin     ""        ""    $4.936  ""    #dd7a7a   #dd7a7a       
 5     5 Hancock      ""        ""    $4.900  ""    #01b5da   #01b5da       
 6     6 Kennebec     ""        ""    $4.955  ""    #ca3338   #ca3338 

有一些额外的专栏需要删除,我留给读者作为练习.

Css相关问答推荐

如何将bslib::card()中的扩展按钮移到右上方,其中full_screen = TRUE?

Css-如何隐藏WP管理菜单上没有css类的第4<;li&>

我应该在哪里放置expo /Reaction本地项目的CSS重置文件?

在主零部件悬停上对子零部件设置Angular 样式

如何在容器查询体中重新定义:Root的CSS自定义属性值?

为什么 width: 100% 在 Flex 父级中缩小这个 div ?

带插值的 Sass 数学函数

使 MUI 自动完成打断长词以适合布局

做一个像CodeSandbox的console那样的可拖拽的split panel

react 样式的条件类名称设置

包含tailwind 中固定纵横比框的内容

在移动设备上touch 屏幕边缘的元素(Material UI)

在同一旋转中以度数变换旋转

Rails 7引擎如何使未编译的样式表可用于托管应用程序?

将一行文本保留为单行 - 换行或不换行

如何定位 CSS 网格布局中的特定列或行?

如何设置表格单元格的最大高度?

将 Fixed div 设置为父容器的 100% 宽度

如何参加滚动事件?

如何水平对齐 span 或 div?