r - 通过 rvest 提取内容的 R web 抓取问题
问题描述
我正在尝试从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。正则表达式对此并不理想,但它比剪断固定长度的字符串要好得多。
推荐阅读
- python - 如何告诉 ubuntu 在主页上运行 __init__.py 而不是 index.html
- powershell - Set-Content 然后 Get-Content 以某种方式更改内容
- r - 如何通过连接获得长数据结构?
- java - 遍历具有数组列表的树,该数组列表包含任意数量的子树作为其子树
- android - 对具有不同方向的多个 RecyclerView 使用相同的布局
- php - 如何让 Laravel 的通知在测试中抛出异常
- django - Django FormSet 显示两个表单集
- sas - 在数据步中循环宏变量
- reactjs - 侧边栏反应菜单汉堡不显示
- android - 有没有办法使用导航组件在 Android 多模块项目中创建隐式深层链接