首页 > 解决方案 > rvest:XPath 和 CSS 不适用于 The Weather Network

问题描述

为了练习,我目前正在尝试从天气网络中抓取一个网站,例如纽约(https://www.theweathernetwork.com/us/weather/new-york/new-york)。到目前为止,我与 X-Path 和 CSS 相处得很好,但我无法为这个网站找出正确的。现在,我只想刮掉表中非常基本的部分:“晴天”、“有阵雨的机会”、“湿雪”等。

到目前为止,我已经尝试过:

library(rvest)

URL <- 'https://www.theweathernetwork.com/us/weather/new-york/new-york'
weather_html <- read_html(URL)

# Trying to use X-Path
forecast1 <- html_nodes(weather_html, xpath = "//*[@class = 'wxRow']/span") %>%
  html_text()

# Trying to use CSS Selector provided by Firefox Inspector Tool
forecast2 <- html_nodes(weather_html, "div.wxColumn:nth-child(1) > div:nth-child(2) > span:nth-child(1)") %>%
  html_text()

# Trying to use the CSS Selector from CSS Selector Gadget
forecast3 <- html_nodes(weather_html, '.wx_description') %>%
  html_text()

这些都不起作用并返回空列表/字符串。

该网站本身似乎可以使用 rvest 进行抓取,因为它正在为网站的另一部分工作:

test <- html_nodes(weather_html, xpath = "//*[@class = 'wx-title']") %>%
  html_text()

正如预期的那样产生“未来7天”。

对不起,如果这是一个非常愚蠢的问题,感谢您的帮助!

标签: rweb-scrapingrvest

解决方案


推荐阅读