【发布时间】:2017-02-17 03:05:48
【问题描述】:
我已经成功地抓取了这个维基百科页面Oscars Nominations 并提取了“提名”下的表格。我可以通过以下代码获取表格:
wiki <- "https://en.wikipedia.org/wiki/89th_Academy_Awards"
text <- wiki %>%
read_html() %>%
html_nodes('//*[@id="mw-content-text"]/table[3]') %>%
html_table()
输出一个“列表”作为名称“文本”
test <- data.frame(one=unlist(text), stringsAsFactors=F)
row.names(test) <- NULL
test <- test[-16,]
nw_lst <- strsplit(test, "\n")
我尝试将结果放在一个 df 中,然后删除一个无用的行,然后在 'nw_lst' 中的换行符正则表达式 '\n' 上的 'strsplit' 输出另一个列表,但有 23 个对应的元素更清晰每个奥斯卡提名的标题如下。然后我想将列表解析为 2 个 df,一个用于最佳影片提名,第二个 df 与其他提名。
oscr.bp <- data.frame(Best.Picture=unlist(nw_lst[[1]]), stringsAsFactors=F)
oscr.bp <- as.data.frame(oscr.bp[-1,], stringsAsFactors=F)
colnames(oscr.bp) <- c("Best.Picture")
所以这是我的问题,一旦我分开提名,我想清理文本。问题是由于某种原因,'stringr' 包中的任何内容都无法删除除电影标题之外的所有不必要的文本。
str_replace_all(oscr.bp$Best.Picture,pattern = "\n", replacement = " ")
str_replace_all(oscr.bp$Best.Picture,pattern = "[\\^]", replacement = " ")
str_replace_all(oscr.bp$Best.Picture,pattern = "\"", replacement = " ")
str_replace_all(oscr.bp$Best.Picture,pattern = "\\s+", replacement = " ")
str_trim(oscr.bp$Best.Picture,side = "both")
但是当我在我的环境中检查 df 的结构并单击蓝色箭头以查看向量类并将鼠标悬停在 chr 向量上时,但它在字符向量中具有奇怪的形状并且在字符串中具有 |__truncated__但在控制台中检查字符串时不可见。
我只是想知道清理这些字符串的最佳方法,还是另一种方法来获取 <ul> 和 <li> 解析下 HTML 节点中每个提名的标题名称?除了查看源代码并使用选择器小工具找到我需要的内容外,对基本的 HTML 代码含义了解不多。
【问题讨论】:
-
“字符向量中有奇怪的形状”——这可能是一个编码问题(参见
?Encoding)。你试过XML包里的html解析功能吗?
标签: r web-scraping rstudio wiki