RCurl包爬蟲學(xué)習(xí)

RCurl包學(xué)習(xí)

基礎(chǔ)



library(RCurl)


d = debugGatherer()
temp <-getURL("http://www.dataguru.cn/",debugfunction=d$update,verbose = TRUE)
cat(d$value()[3])#提交給服務(wù)器的頭信息
cat(d$value()[1])#服務(wù)器地址以及端口號
cat(d$value()[2])#服務(wù)器端返回的頭信息


#將頭部結(jié)果以列表形式輸出
h = basicHeaderGatherer()
txtt=getURL("http://www.dataguru.cn/",headerfunction = h$update)
names(h$value())
h$value()


#將頭部結(jié)果以字符串形式輸出
headers = basicTextGatherer()
txt=getURL("http://www.dataguru.cn/",headerfunction = headers$update)
names(headers$value())#說明是字符串形式
headers$value()#轉(zhuǎn)換成列表cat(headers$value())

#查看Curl的訪問信息
curl = getCurlHandle()
d=getURL("http://www.dataguru.cn/", curl = curl)
getCurlInfo(curl)$response.code
getCurlInfo(curl)


#偽裝自己的操作系統(tǒng)的信息
myheader<-c(
  "User-Agent"="Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.6) ",
  "Accept"="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  "Accept-Language"="en-us",
  "Connection"="keep-alive",
  "Accept-Charset"="GB2312,utf-8;q=0.7,*;q=0.7"
)

#偽裝成UC瀏覽器來進行服務(wù)器的訪問
myheader<-c(
  "User-Agent: NOKIA5700/ UCWEB7.0.2.37/28/999",
  "Accept"="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  "Accept-Language"="en-us",
  "Connection"="keep-alive",
  "Accept-Charset"="GB2312,utf-8;q=0.7,*;q=0.7"
)


d = debugGatherer()
temp <-getURL("http://www.dataguru.cn/",debugfunction=d$update,verbose = TRUE,httpheader=myheader)


#getForm數(shù)據(jù)不用進行加密提交搜索數(shù)據(jù)
#PostForm數(shù)據(jù)需要進行加密提交搜索數(shù)據(jù)

#對百度搜索的網(wǎng)頁進行爬取
url <- getForm("http://www.baidu.com/s?wd=火影")
write.table(url,"url.txt")

getURL函數(shù)中的參數(shù)的解釋

1. verbose:輸出訪問的交互信息
2. httpheader:設(shè)置訪問信息報頭,可自定義httpheader=myheader
3. .encoding="UTF-8" "GBK"
4. debugfunction,headerfunction,curl
5. .params:提交的參數(shù)組
6. dirlistonly:僅讀取目錄
7. followlocation:支持重定向,比如一個網(wǎng)頁<http://www.sina.com > 尾部應(yīng)該是.cn,如果此時輸入錯誤,則會進行報錯,但是加上參數(shù)followlocation=T,則網(wǎng)站會進行自行的跳轉(zhuǎn),跳轉(zhuǎn)到<http://www.sina.cn> 
  8. maxredirs:最大重定向次數(shù),防止跳轉(zhuǎn)鏈接進入一個死循環(huán)

抓取網(wǎng)頁中文亂碼解決方法

1. 抓取頁面時編碼沒有選對;2. 解析表單時編碼沒有選對。解決方法如下:

url="http://data.earthquake.cn/datashare/datashare_more_quickdata_new.jsp"
wp<-getURL(url,.encoding="gb2312") #用網(wǎng)頁本身的編碼
wp2=iconv(wp,"gb2312","UTF-8") #轉(zhuǎn)碼
Encoding(wp2) #UTF-8
doc <- htmlParse(wp2,asText=T,encoding="UTF-8") #選擇UTF-8進行網(wǎng)頁的解析
#查看doc的內(nèi)容時顯示有亂碼,但沒關(guān)系,table的解析結(jié)果沒有亂碼
tables <-readHTMLTable(doc,header=F)



- 網(wǎng)址:http://f.dataguru.cn/thread-356009-1-1.html
- 解決RCurl爬蟲,首先考慮將Rstudio編碼設(shè)置為GB2312,然后再考慮使用上述的方法來進行爬蟲,可能文件在爬取的過程中會顯示是亂碼,但是只要使用xpathSapply函數(shù)進行文件解析最后的結(jié)果是中文的,就能滿足要求。

使用getBinaryURL函數(shù)下載文件

url <- "http://10.0.1.8/images/links/bbs1.gif"
temp <- getBinaryURL(url)#下載一個URL二進制文件

note <- file("hello.gif",open = "wb")#打開一個文件鏈接,對該文件進行二進制寫入操作,注意文件的后綴名
writeBin(temp,note)#將temp寫入note文件中
close(note)#關(guān)閉寫入文件

批量下載文件

library(XML)#XML/HTML解析包
library(RCurl)#RCurl爬蟲包
library(stringr)#文本處理包


url <- "http://rfunction.com/code/1202/"#主界面
html <- getURL(url)#下載二進制html文件
html_doc <- htmlParse(html)#解析html文件
url_html <- str_replace_all(unlist(xpathSApply(doc = html_doc,path = "http://li/a[contains(./text(),'.R')]",fun=xmlValue)),pattern = " ",replacement = "")
#使用xpath查詢語句將.R文件的名字提取出來,unlist將列表扁平化轉(zhuǎn)換為向量,然后使用stringr包中的函數(shù)str_replace_all將字符串向量中的空格刪除掉

temp <- NULL;
#i=1
for(i in 1:length(url_html))
{
url_html_last<- paste(url,url_html[i],sep="");
#將界面的url鏈接和.R文件名字連接起來,成為每個.R文件的url路徑
temp <- getBinaryURL(url_html_last);
#下載每個.R文件的二進制html文件
note <- file(paste(url_html[i]),open="wb")
#打開文件,對該文件進行二進制寫入操作,文件的名字為.R文件的名字
writeBin(temp,note)
#將temp文件寫入連接note中
close(note)
#關(guān)閉文件,運行成功后即可下載完畢
Sys.sleep(time = 30)
#每爬一次休息一會兒
}

使用RCurl爬取豆瓣電影評分



require(RCurl)
library(XML)
x='明日世界'
search <- getForm("https://movie.douban.com/", search_text = x)
searchweb<-htmlParse(search,asText=T,encoding="UTF-8")
#亂碼了 searchweb
searchweb
# 解析搜索結(jié)果頁面 
resnodes<-getNodeSet(searchweb,"http://div[@id='wrapper']//table[1]//a")
#查找id為wrapper的div里面table第一第的數(shù)
resurl<-xmlGetAttr(resnodes[[1]],name="href")
#找到電影url地址
resweb<-getURL(resurl,.encoding="UTF-8")  #上該電影主頁
#得到影片頁面后第二次解析
content<-htmlParse(resweb,encoding="UTF-8")
resnodes<-getNodeSet(content,"http://div[@id='interest_sectl']//p[@class='rating_self clearfix']//strong")
namenodes<-getNodeSet(content,"http://div[@id='content']//h1//span")
#得到影片評分
score<-xmlValue(resnodes[[1]])
name<-xmlValue(namenodes[[1]])
name;
score;

解決中文亂碼的例子

library(RCurl)
library(XML)
library(stringr)

 
url="http://baike.baidu.com/subview/273889/5093882.htm"
wp<-getURL(url,.encoding="gb2312",followlocation=T) #用網(wǎng)頁本身的編碼
#直接進行解析,#加上參數(shù)followlocation=T,支持網(wǎng)頁跳轉(zhuǎn)
doc <- htmlParse(wp,asText=T,encoding="UTF-8")
#doc文件顯示的中文是亂碼,但是不要緊,使用xpath查詢結(jié)果是正常的
xpathSApply(doc,"http://dt[@class='basicInfo-item name']",xmlValue)#查詢電影的基礎(chǔ)信息字段名字
xpathSApply(doc,"http://dd[@class='basicInfo-item value']",xmlValue)#查詢電影的基礎(chǔ)信息的值
#二者的長度應(yīng)該是相等的



####考慮是否需要轉(zhuǎn)碼的程序
wp2=iconv(wp,"gb2312","UTF-8") #轉(zhuǎn)碼
Encoding(wp2) #UTF-8
doc <- htmlParse(wp2,asText=T,encoding="UTF-8") #選擇UTF-8進行網(wǎng)頁的解析
#查看doc的內(nèi)容時顯示有亂碼,但沒關(guān)系,table的解析結(jié)果沒有亂碼
tables <-readHTMLTable(doc,header=F)




#使用百度搜索爬蟲的例子
getwd()
setwd("./我的R/RCurl包學(xué)習(xí)/")
#先使用百度搜索一個例子,比如“碟中諜”,獲取參數(shù)
url <- "https://www.baidu.com/s?wd=%E7%A2%9F%E4%B8%AD%E8%B0%8D&rsv_op=LteD3w8Y4BopY7Hr664Ak1Oh37Ol8AKpP2A187anxe7YHooBmDGaNkS96wCFnFd7XgAn50j824I648lYQzUlqvED4jYBAvjPX8d93MMky05546hIl122t2pM7269NN5Q7bRIMidr695Ybd0UgCQNjgVcw2y4dt2wMrk29jh0IG7OXWwuj88fRg&tn=91514441_hao_pg&ie=gbk"
#得到url鏈接的參數(shù)
getFormParams(url)
#修改參數(shù)wd,即為百度搜索的內(nèi)容參數(shù)wd,其他參數(shù)復(fù)制粘貼進函數(shù)中,然后運行
wp <- getForm("http://www.baidu.com/s",wd="RCurl",rsv_op ="LteD3w8Y4BopY7Hr664Ak1Oh37Ol8AKpP2A187anxe7YHooBmDGaNkS96wCFnFd7XgAn50j824I648lYQzUlqvED4jYBAvjPX8d93MMky05546hIl122t2pM7269NN5Q7bRIMidr695Ybd0UgCQNjgVcw2y4dt2wMrk29jh0IG7OXWwuj88fRg" ,tn ="91514441_hao_pg",ie ="gbk" )
doc <- htmlParse(wp,asText=T,encoding="UTF-8")
write.table(wp,"百度搜索例子.txt")


#使用淘寶搜索的頁面爬取的例子
url <- "https://s.taobao.com/search?q=%E5%9B%BE%E8%A7%A3%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.50862.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20161029"
#得到url鏈接的參數(shù)
getFormParams(url)
#修改參數(shù)wd,即為淘寶搜索的內(nèi)容參數(shù)q,其他參數(shù)復(fù)制粘貼進函數(shù)中,然后運行
wp <- getForm("https://s.taobao.com/search?", q="火影",imgfile="",commend="all" ,ssid="s5-e",search_type="item", 
              sourceId=
              "tb.index" ,
              spm =
              "a21bo.50862.201856-taobao-item.1" ,
              ie =
              "utf8" ,
              initiative_id= 
              "tbindexz_20161029"  )
write.table(wp,"淘寶搜索例子.txt")


#使用淘寶搜索的頁面爬取的例子
url <- "https://s.taobao.com/search?q=%E5%9B%BE%E8%A7%A3%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.50862.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20161029"
#得到url鏈接的參數(shù)
getFormParams(url)
#修改參數(shù)wd,即為淘寶搜索的內(nèi)容參數(shù)q,其他參數(shù)復(fù)制粘貼進函數(shù)中,然后運行
wp <- getForm("https://s.taobao.com/search?", q="火影",imgfile="",commend="all" ,ssid="s5-e",search_type="item", 
              sourceId=
                "tb.index" ,
              spm =
                "a21bo.50862.201856-taobao-item.1" ,
              ie =
                "utf8" ,
              initiative_id= 
                "tbindexz_20161029"  )
write.table(wp,"淘寶搜索例子.txt")



library(RCurl)
library(XML)
#Rstudio 需要設(shè)置默認的編碼格式為gb2312,即網(wǎng)頁的默認編碼格式
#百度新聞查詢結(jié)果數(shù)據(jù)是亂碼格式,考慮解決的辦法
#試試新浪首頁
url <- "http://www.sina.com.cn/"
wp<-getURL(url,.encoding="gb2312",followlocation=T) #用網(wǎng)頁本身的編碼
#wp2 <- iconv(wp,"gb2312","UTF-8")#轉(zhuǎn)碼
#Encoding(wp2)#編碼
#直接進行解析,#加上參數(shù)followlocation=T,支持網(wǎng)頁跳轉(zhuǎn)
doc <- htmlParse(wp,asText=T,encoding="UTF-8")#解析
#doc文件顯示的中文是亂碼,但是不要緊,使用xpath查詢結(jié)果是正常的
#write.table(xpathSApply(doc,path = "http://a",xmlValue),"百度新聞.txt")
#xpathSApply(doc,path="http://ul[@class='list-a news_top']/li/a",xmlValue)
#xpathSApply(doc,path="http://ul[@class='list-a news_bottom']/li/a",xmlValue)
xpathSApply(doc,path="http://div[@class='top_newslist']/ul/li/a",xmlValue)







#使用RCurl爬取豆瓣電影評分
require(RCurl)
library(XML)
x='明日世界'
search <- getForm("https://movie.douban.com/", search_text = x)
searchweb<-htmlParse(search,asText=T,encoding="UTF-8")
#亂碼了 searchweb
searchweb
# 解析搜索結(jié)果頁面 
resnodes<-getNodeSet(searchweb,"http://div[@id='wrapper']//table[1]//a")
#查找id為wrapper的div里面table第一第的數(shù)
resurl<-xmlGetAttr(resnodes[[1]],name="href")
#找到電影url地址
resweb<-getURL(resurl,.encoding="UTF-8")  #上該電影主頁
#得到影片頁面后第二次解析
content<-htmlParse(resweb,encoding="UTF-8")
resnodes<-getNodeSet(content,"http://div[@id='interest_sectl']//p[@class='rating_self clearfix']//strong")
namenodes<-getNodeSet(content,"http://div[@id='content']//h1//span")
#得到影片評分
score<-xmlValue(resnodes[[1]])
name<-xmlValue(namenodes[[1]])
name;
score;

#爬取豆瓣電影top250
library(stringr)
library(RCurl)
library(XML)
url <- paste("https://movie.douban.com/top250?start=",seq(0,225,by=25),"&filter=",sep = "")
y <- NULL;
for (i in 1:length(url)){
wp<-getURL(url[i],.encoding="gb2312",followlocation=T) 
doc <- htmlParse(wp,asText=T,encoding="UTF-8")#解析
#電影名字
name <- xpathSApply(doc,path="http://span[@class='title'][1]",xmlValue)
#評分
score <- xpathSApply(doc,path="http://span[@class='rating_num' and @property='v:average']",xmlValue)
#上映時間
time <- str_extract(xpathSApply(doc,path="http://div[@class='bd']/p[@class='']",xmlValue),pattern = '[1-2][0-9]{3}')
#生產(chǎn)地區(qū)
for(j in 1:25){
country[j] <- str_split(str_extract(xpathSApply(doc,path="http://div[@class='bd']/p[@class='']",xmlValue),pattern = '[1-2][0-9].*/.*/'),pattern = "/")[[j]][2]
}
country <- str_trim(country)
x <- cbind(name,score,time,country)
y <- rbind(y,x)
    }
y <- as.data.frame(y)#存入數(shù)據(jù)框y

#豆瓣大眾點評
#報頭設(shè)置非常重要,爬蟲一定要偽裝,另外for循環(huán)一定要間隔休息
myheader<-c(
  "User-Agent"="Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.6) ",
  "Accept"="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  "Accept-Language"="en-us",
  "Connection"="keep-alive",
  "Accept-Charset"="GB2312,utf-8;q=0.7,*;q=0.7"
)

#url <- "http://t.dianping.com/list/guangzhou?q=%E7%94%B5%E5%BD%B1"
url <- "https://www.douban.com/"
url <- paste(url,"search?q=數(shù)學(xué)分析",sep = "")
wp<-getURL(url,.encoding="gb2312",followlocation=T,httpheader=myheader) 
doc <- htmlParse(wp,asText=T,encoding="UTF-8")#解析
xpathSApply(doc,path = "http://div[@class='result']")

總結(jié):

  • R語言做爬蟲,如果是爬靜態(tài)網(wǎng)頁,使用RCurl包和XML包就能很好解決,主要是使用Xpath查詢語句和正則表達式,另外,最好是在linux環(huán)境中進行R爬蟲,考慮到中文編碼的問題,最好環(huán)境是使用Rstudio-server環(huán)境。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容