作者miao2361 (Miao)
看板R_Language
标题[问题] 爬批踢踢文章内容
时间Wed Apr 1 17:44:26 2015
[问题类型]:
程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
[软体熟悉度]:
使用者(已经有用R 做过不少作品)
[问题叙述]:
请简略描述你所要做的事情,或是这个程式的目的
问题一
用httr、XML套件想要把批踢踢的文章们存成.txt档以利後续text mining
但是八卦板因为有「确认已满18岁」的网页而无法存出文章
问题二
关於RCurl的问题(详见以下)
问题一
library(XML)
library(httr)
start <- regexpr('www', line)[1]
end <- regexpr('html', line)[1]
if(start != -1 & end != -1){
url <- substr(line, start, end+3)
html <- content(GET(url), encoding="UTF8")
doc <- xpathSApply(html, "//div[@id='main-content']", xmlValue)
name <- strsplit(url, '/')[[1]][4]
write(doc, gsub('html', 'txt', name))
}
# 当 读入八卦板以外的批踢踢文章网址
line = "
https://webptt.com/cn.aspx?n=bbs/StupidClown/M.1427811176.A.552.html"
工作路径中会出现一个新的txt档,其中存着这篇笨版文章的内容
# 当 读入八卦板网址
line = "
https://webptt.com/cn.aspx?n=bbs/Gossiping/M.1427816656.A.450.html"
存下来的txt档里面却是空的。
研判应该是八卦板的十八岁限制网页造成
https://webptt.com/cn.aspx?n=bbs/Gossiping/M.1427816656.A.450.html
想请问版上高手如何跳过这个网页呢?
问题二
原程式码
url <- substr(line, start, end+3)
html <- content(GET(url), encoding="UTF8")
doc <- xpathSApply(html, "//div[@id='main-content']", xmlValue)
name <- strsplit(url, '/')[[1]][4]
write(doc, gsub('html', 'txt', name))
原本想用RCurl套件来做第二行
html <- htmlParse(getURL(url), encoding='UTF-8')
存出来的html却失败
> html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr>
<center>nginx</center>
</body>
</html>
但後来改成用httr套件的content()和GET()就可以了,却不明白为什麽XD
---
自己研究了一下,以上问题可能会触碰到 HTTP request header的范畴,
但我过去并没有学过这方面的知识
不知道版上各位大大有没有推荐的文章可以介绍自学呢?
非常感恩~~~~!!
[环境叙述]:
> sessionInfo()
R version 3.1.2 (2014-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 111.80.167.159
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1427881473.A.71F.html
※ 编辑: miao2361 (111.80.167.159), 04/01/2015 17:59:17
1F:推 andrew43: 把 over18 这个 cookie 的值写入 1 应该就可以了。 04/01 18:52
2F:推 andrew43: 不过我不了解在 R 这端怎麽做。 04/01 18:52
3F:→ miao2361: 恩恩~有看过python的code这样写,但R不知如何解... 04/01 19:13
5F:推 celestialgod: ,请参考rcurl的website,目前人在外面,不方便测 04/01 20:04
6F:推 celestialgod: 试,抱歉。 04/01 20:04
8F:→ miao2361: 非常感谢楼上!解开了,比想像中简单太多XD 程式码如下 04/08 17:54
9F:→ miao2361: GET(url, config=set_cookies("over18"="1"),...)即可 04/08 17:54
10F:→ celestialgod: 不客气,谢谢您的回覆 04/08 20:17