RCurl網絡數據抓取


觀察基礎信息(服務器信息和提交給服務器的信息)

d=debugGatherer()
xpath="http://123.sogou.com/"
url=getURL(xpath,debugfuNction=d$update,verbose=T)
cat(d$value()[1])#服務器地址以及端口號
cat(d$value()[2])#服務器返回的頭信息
cat(d$value()[3])#提交給服務器的頭信息

觀察是否連接到該網址。

curl=getCurlHandle()
url=getURL(xpath,curl=curl,httpheader=myheader)
getCurlInfo(curl)$response.code

顯示為200 表示獲取成功。

 有時候網頁獲取信息不全,可能是頭信息導致的錯誤

#設置頭信息
myheader<-c(
"User-Agent"="Mozilla/5.0 (Linux; U; Android 2.3.3; zh-cn; HTC_DesireS_S510e Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
"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"
)

xpath="http://t.dianping.com/list/guangzhou?q=%E7%94%B5%E5%BD%B1"
url=getURL(xpath,httpheader=myheader)

可以觀察增加頭信息和不添加頭信息之間的區別

有時候網頁獲取信息亂碼,總共三種處理方法。第一,增加參數 .encoding(觀察html的編碼情況)  第二,可以嘗試設置頭信息去解決。 第三,windows 出現亂碼問題,需在Linux系統下執行

通過與XML包的結合也可以直接抓取表格信息

xpath="http://www.hbksw.com/html/13/26369.shtml"
url=getURL(xpath,httpheader=myheader,.encoding="gb2312")
write(url,"f://url.txt")
doc<-htmlParse(url,asText=T)
tables<-readHTMLTable(doc,which=4);tables

正則表達式的一些使用

# \ 轉義字符 . 除了換行后的任意字符 ^ 開頭 $ 結尾 * 0個或者多個
# + 一個或者多個 ? 0個或者一個
#正則表達式的匹配
pattern="[A-Za-z0-9\\._%+-]+@[A-Za-z0-9\\._%+-]+\\.[A-Za-z]{2,4}"
list=c("sunshine@.163.com","niubi","421946059@qq.com")
list1<-paste(list,collapse=",")
grepl(pattern,list)
grep(pattern,list1)
regexpr(pattern,list1)
regexec(pattern,list1)
gregexpr(pattern,list1)

通過正則表達式抓取到自己想要數據的位置,通過字符串分割去提取


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM