我想用R来计算html文章中的字数。像标题这样的抓取数据效果很好,我能够下载这些文章(代码如下)。现在我想数一下所有这些文章中的字数,例如“默克尔”这个词。
这看起来有点复杂。我能够让它与标题一起工作(将每个标题放在一个向量中并计算单词),但这太详细了,代码太多(因为如果搜索中有超过1个页面的结果,我必须手动将每个月的标题放在一起),这就是为什么我不会在这里发布所有代码的原因(我相信这很容易,但那是另一个问题)。
我想我搞砸了一些东西,这就是为什么我不能对html文章做同样的事情。不同的是,我直接刮掉了标题,但我必须先下载html文件。
那么,我怎样才能浏览我的10000个(这里只有45个) html页面,并找到一些漂亮的键盘呢?一月份的例子;我下载了这段代码的文章;
library(xml2)
library(rvest)
url_parsed1 <- read_html("http://www.sueddeutsche.de/news?search=Fl%C3%BCchtlinge&sort=date&dep%5B%5D=politik&typ%5B%5D=article&sys%5B%5D=sz&catsz%5B%5D=alles&time=2015-01-01T00%3A00%2F2015-12-31T23%3A59&startDate=01.01.2015&endDate=31.01.2015")
link_nodes <- html_nodes(url_parsed1, css = ".entrylist__link")
html_links <- html_attr(link_nodes, "href")
getwd()
dir.create("html_articles")
setwd("html_articles")
for (url in html_links) {
newName <- paste (basename(url),".html")
download.file(url, destfile = newName)
}非常感谢你的帮助!
发布于 2018-01-03 23:04:06
我希望我正确理解了你的问题:
library(xml2)
library(rvest)
library(XML)
url_parsed1 <- read_html("http://www.sueddeutsche.de/news?search=Fl%C3%BCchtlinge&sort=date&dep%5B%5D=politik&typ%5B%5D=article&sys%5B%5D=sz&catsz%5B%5D=alles&time=2015-01-01T00%3A00%2F2015-12-31T23%3A59&startDate=01.01.2015&endDate=31.01.2015")
link_nodes <- html_nodes(url_parsed1, css = ".entrylist__link")
html_links <- html_attr(link_nodes, "href")
getwd()
dir.create("html_articles")
setwd("html_articles")
for (url_org in html_links) {
# url_org <- html_links[1]
newName <- paste (basename(url_org),".html")
download.file(url_org, destfile = newName)
# Read and parse HTML file
doc.html <- htmlTreeParse(url_org,
useInternal = TRUE)
# Extract all the paragraphs (HTML tag is p, starting at
# the root of the document). Unlist flattens the list to
# create a character vector.
doc.text = unlist(xpathApply(doc.html, '//p', xmlValue))
# Replace all \n by spaces
doc.text = gsub('\\n', ' ', doc.text)
# Join all the elements of the character vector into a single
# character string, separated by spaces
doc.text = paste(doc.text, collapse = ' ')
# count the occurences of the word "Merkel in that hmtl
str_count(doc.text,"Merkel")
}https://stackoverflow.com/questions/48079467
复制相似问题