r - Rvest 抓取不同行数的谷歌新闻
问题描述
我正在使用 Rvest 来抓取谷歌新闻。
但是,我不时在不同的关键字上遇到元素“时间”中的缺失值。由于缺少值,因此对于抓取结果的数据框,最终会出现“不同的行数错误”。
无论如何要为这些缺失值填写 NA 吗?
下面是我正在使用的代码示例。
html_dat <- read_html(paste0("https://news.google.com/search?q=",Search,"&hl=en-US&gl=US&ceid=US%3Aen"))
dat <- data.frame(Link = html_dat %>%
html_nodes('.VDXfz') %>%
html_attr('href')) %>%
mutate(Link = gsub("./articles/","https://news.google.com/articles/",Link))
news_dat <- data.frame(
Title = html_dat %>%
html_nodes('.DY5T1d') %>%
html_text(),
Link = dat$Link,
Description = html_dat %>%
html_nodes('.Rai5ob') %>%
html_text(),
Time = html_dat %>%
html_nodes('.WW6dff') %>%
html_text()
)
解决方案
在不知道您正在查看的确切页面的情况下,我尝试了第一个 Google 新闻页面。
在 Rvest 页面中,html_node
(没有 s)将始终返回一个值,即使它是 NA。因此,为了保持向量的长度相同,需要为所有所需的数据节点找到共同的父节点。然后从这些节点中的每一个解析所需的信息。
假设 Title 节点是最完整的,上升 1 级xml_parent()
并尝试检索相同数量的描述节点,这不起作用。然后尝试使用 2 级xml_parent() %>% xml_parent()
,这似乎有效。
library(rvest)
url <-"https://news.google.com/topstories?hl=en-US&gl=US&ceid=US:en"
html_dat <- read_html(url)
Title = html_dat %>% html_nodes('.DY5T1d') %>% html_text()
# Link = dat$Link
Link = html_dat %>% html_nodes('.VDXfz') %>% html_attr('href')
Link <- gsub("./articles/", "https://news.google.com/articles/",Link)
#Find the common parent node
#(this was trial and error) Tried the parent then the grandparent
Titlenodes <- html_dat %>% html_nodes('.DY5T1d') %>% xml_parent() %>% xml_parent()
Description = Titlenodes %>% html_node('.Rai5ob') %>% html_text()
Time = Titlenodes %>% html_node('.WW6dff') %>% html_text()
answer <- data.frame(Title, Time, Description, Link)
推荐阅读
- python - ThreadPoolExecutor 返回错误
- firebase - 从 Flutter 中的嵌套 Firestore 获取一次性读取数据
- linux - 短格式的 Linux 打印正常运行时间
- python - 在 C# 中解释 Python 字节码(带有精细控制)
- node.js - 如何使用 nodejs 应用程序中的 REST API 将比特流上传到 DSpace?
- kubernetes - 使用 helm 迁移数据库
- python - 如何解释这种在 python 文档中编写参数的方式?
- python - 从python中的联合分布制作边际分布
- python - 在python中的矩阵中的相同值之间绘制网格线
- python - 如何按列中的分组值过滤数据框中的值