gpt4 book ai didi

css - 如何使用rvest中的节点和类提取网页数据

转载 作者:行者123 更新时间:2023-12-05 03:21:42 29 4
gpt4 key购买 nike

我正在网站上执行网络抓取,并且已经能够获取基本数据,但我现在需要从页面的更复杂部分收集数据。

我正在使用 rvest 从 AAA 汽油价格网站提取数据:

https://gasprices.aaa.com/

我现在正在尝试拉取县级数据,该数据仅显示在 map 上(如果将光标悬停在单个县上。我需要获取不同州各个县的县级汽油价格。例如,如果您点击缅因州,转到缅因州页面 ( https://gasprices.aaa.com/?state=ME ),我需要通过网络抓取 Aroostook( map 上最北端的县)的价格。

我已经能够使用 rvest 提取都市区(页面下方)的数据,使用 html_nodes和节点“td”。但是, map 的代码更为复杂。开发人员工具(在 Chrome 中)提供了 <td class="fm-tooltip-comment">$4.928</td,而不是简单的“td”节点。与价格一致(截至本文发布之日,Aroostook 的当前价格为 4.928 美元)。我似乎无法用 rvest 包来提取它。

我读到可以使用该类,或者其他人建议使用css代码在rvest中指定它,但我不熟悉如何这样做。提取都市区数字很简单,但 map 中嵌入的县级价格似乎不太容易访问。

有没有办法提取这个县级数据,以便我可以在 R 中进行网络抓取?而且,对于我必须选择的所有县/州,这是否可以重复?我需要 css 代码吗?如果需要,我该如何访问它/正确编写它以供 rvest 使用?

最佳答案

看起来您要查找的信息存储在“index.php”文件中,该文件在网页加载时下载。缅因州的当前链接是“https://gasprices.aaa.com/index.php?premiumhtml5map_js_data=true&map_id=21&r=89346&ver=5.9.3”。
我不确定 r=89346 值的用途,可能是时间戳、跟踪 ID、临时 token (以防止网络抓取)等。我怀疑此 URL 会更改,因此您可能需要使用浏览器上的开发人员工具来获取当前网址。
另外,map_id 指的是州,但我不知道有没有道理,佛罗里达州是 1,北卡罗来纳州是 35,缅因州是 21。

下载此文件,然后提取 JSON 数据并进行转换。数据以 {"st1": 开头,以 }} 结尾。

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 - 如何使用rvest中的节点和类提取网页数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72890307/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com