问题描述
我正在尝试从https://careers.microsoft.com/us/en/search-results中提取内容,并从页面中获取标题,信息等
urlString <- "https://careers.microsoft.com/us/en/search-results?"
getHTML <- xml2::read_html(urlString)
t2 <- getHTML %>% html_text() %>% stringr::str_sub(start = 8027,end = 65679)
jsonWeb <- jsonlite::fromJSON(t2)
df <- jsonWeb$data$jobs
有没有更优雅的方法?就像提取phApp.ddo {}的json 非常感谢
解决方法
通过网络抓取这样的网站不可能获得可靠的结果,因为您无法控制要抓取的内容。但是,通过子字符串索引进行操作是一场灾难,因为动态内容中的几乎所有更改都将破坏您的代码(实际上,您的代码对我不起作用,因为提供给我的json字符串略短,所以我拖了尾随无法解析的垃圾)。
一种更可靠的解决方案(尽管请参见下面的注意事项)是在json字符串的开头和结尾处找到有用的定界符,您可以使用这些定界符来切掉不需要的部分。
urlString <- "https://careers.microsoft.com/us/en/search-results?"
getHTML <- xml2::read_html(urlString)
json <- jsonlite::fromJSON(strsplit(strsplit(html_text(getHTML),"phApp\\.ddo = ")[[1]][2],"; phApp")[[1]][1])
json$eagerLoadRefineSearch$data$jobs
#> # A tibble: 50 x 27
#> country subCategory industry title multi_location type orgFunction
#> <chr> <chr> <lgl> <chr> <list> <lgl> <lgl>
#> 1 United~ Software E~ NA Prin~ <chr [1]> NA NA
#> 2 United~ Art NA Lead~ <chr [1]> NA NA
#> 3 India Support En~ NA Supp~ <chr [1]> NA NA
#> 4 Romania Support En~ NA Micr~ <chr [2]> NA NA
#> 5 China Solution S~ NA Seni~ <chr [1]> NA NA
#> 6 United~ Software E~ NA Soft~ <chr [1]> NA NA
#> 7 India Support En~ NA Supp~ <chr [1]> NA NA
#> 8 United~ Software E~ NA Seni~ <chr [1]> NA NA
#> 9 Japan Marketing ~ NA Full~ <chr [1]> NA NA
#> 10 United~ Software E~ NA Seni~ <chr [1]> NA NA
#> # ... with 40 more rows,and 20 more variables: experience <chr>,#> # locale <chr>,multi_location_array <list>,jobSeqNo <chr>,#> # postedDate <chr>,searchresults_display <lgl>,#> # descriptionTeaser <chr>,dateCreated <chr>,state <chr>,#> # targetLevel <chr>,jd_display <lgl>,reqId <lgl>,badge <chr>,#> # jobId <chr>,isMultiLocation <lgl>,jobVisibility <list>,#> # mostpopular <dbl>,location <chr>,category <chr>,#> # locationLatlong <lgl>
我同意,如果只请求json会更好,但是在这种情况下,页面是在服务器端构建的,因此对于提供json的API而言,没有独立的xhr请求,因此您需要雕刻json投放的HTML中。正则表达式不是理想的选择,但是它比截取固定长度的字符串要好得多。
,使用V8
包在页面上运行JS脚本以获取phApp
对象:
library(rvest)
library(V8)
pg <- read_html("https://careers.microsoft.com/us/en/search-results")
scripts <- pg %>% html_nodes(xpath = "//script[contains(.,'phApp')]") %>% html_text()
ct <- v8()
ct$eval("var phApp = {}")
for (js in scripts) ct$eval(js)
data <- ct$get("phApp")
jobs <- data$ddo$eagerLoadRefineSearch$data$jobs