从动态网站中提取所有实例的数据

Extract data for all the instances from a dynamic website

我正在尝试从 https://www.xercise4less.co.uk/find-a-gym/ 抓取所有健身房位置的数据。

在开发人员工具中,我找到了一个指向 Web API URL 的指针,它应该将此信息存储在 https://www.xercise4less.co.uk/Umbraco/Api/FindAGymApi/GetAll 下,但是当我在浏览器中 运行 它时,我得到

The 'ObjectContent`1' type failed to serialize the response body for content type 'text/xml; charset=utf-8'

同样,如果我运行下面的代码:

# user_agent argument is optional here and results are the same whether I include it or not 
httr::GET('https://www.xercise4less.co.uk/Umbraco/Api/FindAGymApi/GetAll',  httr::user_agent("httr"))

关于如何解决这个问题有什么想法吗?

或者,我可以(几乎)通过

访问所有健身房 ID
library(rvest)
library(magrittr)

url <- "https://www.xercise4less.co.uk/find-a-gym/"
my_pg <- read_html(url) 
my_pg %>% html_nodes('select > option')

但是我仍然不确定如何遍历所有 ID 以获得 coordinates/locations 的完整列表。 感谢指点。

这段代码应该可以满足您的需求,或者至少更接近您的需求。我借用了你的第二个例子。我可能会删除第一行。

final <- as.character(my_pg %>% html_nodes('select > option'))
df <- data.frame(do.call(rbind, strsplit(final, '>', fixed=TRUE)), stringsAsFactors = FALSE)
df$X1 <-sapply(strsplit(df$X1, '=', fixed=TRUE), "[", 2 )
df$X1 <- gsub('[\"]', '', df$X1)

df$X2 <-sapply(strsplit(df$X2, '<', fixed=TRUE), "[", 1 )


df = subset(df, select = -c(X3) )

输出

    X1                             X2
1 <NA>              Select a location
2 1104        Xercise4Less Bolton Gym
3 1248      Xercise4Less Bradford Gym
4 1249 Xercise4Less Brierley Hill Gym
5 1250       Xercise4Less Bristol Gym
6 1251       Xercise4Less Burnley Gym

你已经差不多了,你只需要设置服务器期望的正确请求header,然后你就可以获得所有健身房的所有信息。

library(httr)

headers = c('Accept'='application/json, text/javascript, */*; q=0.01')
r <- content(httr::GET(url = 'https://www.xercise4less.co.uk/Umbraco/Api/FindAGymApi/GetAll', httr::add_headers(.headers=headers)))
print(r)