# Load required packages
library(rvest)
library(dplyr)
# Define the URL
url <- "https://aqicn.org/city/kathmandu"
# Read the HTML content of the page
webpage <- read_html(url)
# Extract AQI forecast table
tables <- webpage %>%
html_element("div.section-content") %>%
html_text()
IM使用此代码,但它只是将我返回带有Na值的Tibble,但在网站中实际上没有任何NA值。有人可以帮助我吗?
ime使用api
library(httr); library(jsonlite)
token <- "demo" # your token here
city <- "here" #"@14866" # City name or code
url <- paste0("https://api.waqi.info/feed/", city,"/")
response <- GET(url, query = list(token = token))
if (http_status(response)$category == "Success") {
result <- fromJSON(content(response, "text", encoding = "UTF-8"))
} else {
print(paste("Error:", http_status(response)$message))
}
尽管我发现,如果我使用正确的城市代码
@14866
,但
here
或shanghai
工作似乎不起作用。
Method2由于它没有直接与免费的API合作,我必须使用网络中使用的方法
library(httr)
library(jsonlite)
url <- "https://api2.waqi.info/api/feed/@14866/aqi.json"
headers <- c(
"Accept" = "*/*",
"Accept-Encoding" = "gzip, deflate, br, zstd",
"Accept-Language" = "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6,zh;q=0.5",
"Content-Type" = "application/x-www-form-urlencoded",
"Origin" = "https://aqicn.org",
"Referer" = "https://aqicn.org/",
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"
)
response <- POST( # Make the POST request
url = url,
add_headers(.headers = headers),
body = list(),
encode = "form"
)
if (status_code == 200) { # If successful, parse the JSON content
result2 <- fromJSON(content(response, "text", encoding = "UTF-8"))
} else {
print("Request failed")
print(content(response, "text"))
}