抓取请求 rvest 同意 cookie 的站点

Dom*_*gel 6 r rvest

我想抓取(使用rvest)一个要求用户同意设置 cookie 的网站。如果我只是抓取页面,则 rvest 只会下载弹出窗口。这是代码:

library(rvest)
content <- read_html("https://karriere.nrw/stellenausschreibung/dba41541-8ed9-4449-8f79-da3cda0cc07c") 
content %>% html_text()
Run Code Online (Sandbox Code Playgroud)

结果似乎是请求同意的弹出窗口的内容。

有没有办法忽略或接受弹出窗口或提前设置 cookie 以便我可以访问网站的正文?

Dat*_*kel 4

正如所建议的,该网站是动态的,这意味着它是由 JavaScript 构建的。通常从 .js 文件重建(或者直接不可能)这是非常耗时的,但在这种情况下,您实际上可以在浏览器的“网络分析”功能中看到,有一个非隐藏的提供您想要的信息的 api。这是对 api.karriere.nrw 的请求。

因此,您可以使用 url 的 uuid(数据库中的标识符)并向 api 发出简单的 GET 请求,然后直接访问源代码,而无需通过 RSelenium 进行渲染,这需要额外的时间和资源。

但要友善,并向他们发送某种联系方式,以便他们可以告诉你停止。

library(tidyverse)
library(httr)
library(rvest)
library(jsonlite)
headers <- c("Email" = "johndoe@company.com")

### assuming the url is given and always has the same format
url <- "https://karriere.nrw/stellenausschreibung/dba41541-8ed9-4449-8f79-da3cda0cc07c"

### extract identifier of job posting
uuid <- str_split(url,"/")[[1]][5]

### make api call-address
api_url <- str_c("https://api.karriere.nrw/v1.0/stellenausschreibungen/",uuid)

### get results
response <- httr::GET(api_url,
                    httr::add_headers(.headers = headers))
result <- httr::content(response, as = "text") %>% jsonlite::fromJSON()
Run Code Online (Sandbox Code Playgroud)