如何从简体中文网站上抓取内容?

时间:2019-08-24 02:29:14

标签: r rvest cjk

我已经在各种英语网站上成功测试了此代码。但是,当我尝试从简体中文网站中抓取内容时,数据在CSV文件中显示为乱码。此外,文章的正文分布在Excel中的多行中,没有包含在一个单元格中。有人可以帮忙吗?

install.packages("rvest")
library(rvest)

###specifying the URL for the website you want to scrap ###
url <-'https://new.qq.com/omn/20190823/20190823A02W4Q00.html'

##reading the HTML code from the website
webpage <- read_html(url)

###using CSS selectors to scrape the title
title_html <- html_nodes(webpage,'h1')

###Converting the main text data to text
title_data <- html_text(title_html)

###using CSS selectors to scrape the body
text_html <- html_nodes(webpage,'.one-p')

###Converting the body data to text
text_data <- html_text(text_html)


d <- data.frame(text_data)
write.csv(d,"chinesetext.csv")

1 个答案:

答案 0 :(得分:0)

大多数这些问题是由编码引起的。我尝试使用guess_encoding函数。它猜到了UTF-8编码。但这不起作用。您可以看到此代码。

Error in doc_parse_raw(x, encoding = encoding, base_url = base_url, as_html = as_html,  : 
input conversion failed due to input error, bytes 0xC8 0xDD 0x2D 0x2D [6003]

因此,我使用扩展Unix代码进行了更改。它正在工作。

url <-'https://new.qq.com/omn/20190823/20190823A02W4Q00.html'
webpage <- read_html(url, encoding="euc-cn")
title_html <- html_nodes(webpage,'h1')
title_data <- html_text(title_html)
title_data
[1] "“六稳”政策显效 抗压能力增强"

也许您想用中文转换数据框。在您的代码之前,添加此代码。然后您可以在全球环境中看到中文。

Sys.setlocale("LC_ALL", "Chinese")
相关问题