共計 2403 個字符,預計需要花費 7 分鐘才能閱讀完成。
R 語言爬蟲如何爬取招聘網站的招聘信息,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
R 語言爬取招聘網上的招聘信息,雖然 R 做爬蟲確實沒 python 專業,但是有一個包 rvest 我覺得還不錯,我嘗試爬取 58 同城招聘網上的數據。
rvest 包, 用到的函數有:
read_html(),
html_nodes(),
html_text(),
html_attr();
具體源代碼如下:
##### 加載相關包 ############
library(xml2)
library(rvest)
library(base)
下面獲得每個子網站的地址
#58 同城主網站網址
url – http://jingzhou.58.com/?utm_source=market spm=b-31580022738699-pe-f-829.hao360_101
web -read_html(url,encoding = utf-8)
xpath – div.col3 a
############# 子網站網址 ###########
title -web% %html_nodes(xpath)% %html_text()
link -web% %html_nodes(xpath)% %html_attr(href)
########## 對子網站翻頁 ########
id -c(1:20)
pn -paste0(pn ,id, /)# 下載的網址有規律地缺失 paste0() 是字符串連接函數
########### 清理網址中的缺失值 #########
for (http in 1:length(link)) {
httplink -substr(link[http],1,4)
if(httplink== http){link[http] -substr(link[http], ,link[http])}
}
link -na.omit(link)
filename – E:\\ 工作簿 1.csv #本地文件路徑,用以存儲下載的數據
job – 職位 company – 公司 location – 地域 time – 發布時間
data -data.frame(job,company,location,time)
len -max(length(job),length(company),length(location),length(time))
######## 從子網站爬取數據 ##########
for (i in 1:length(link)) {
link0 -paste0(http://jingzhou.58.com ,link[i],pn, utm_source=market spm=b-31580022738699-pe-f-829.hao360_101 PGTID=0d100000-00d9-7474-25a7-e93482a12861 ClickID=xxxx )
link1 -paste0(http://jingzhou.58.com ,link[i],pn, ?utm_source=market spm=b-31580022738699-pe-f-829.hao360_101 PGTID=0d100000-00d9-7fce-21b0-b8956617e76f ClickID=xxxx )
##### 網址最后的變化 ###########
for (j in 1:length(link)) {
link0 -gsub(xxxx ,j,link0)
link1 -gsub(xxxx ,j,link1)
##### 網站名的兩種類型用 trycatch() 消除錯誤 #####
for (k in 1:length(pn)) {
tryCatch(
{web -read_html(link0[k],encoding = utf-8 )},
error={web -read_html(link1[k],encoding = utf-8 )})
########### 提取需要的變量 ###########
job_path – dt a #獲取職位節點
company_path – dd.w271 a #獲取公司節點
location_path – dd.w96 #獲取地域節點
time_path – dd.w68 #獲取發布時間節點
job -web% %html_nodes(job_path)% %html_text();
company -na.omit(web% %html_nodes(company_path)% %html_text());
location -web% %html_nodes(location_path)% %html_text();
time -web% %html_nodes(time_path)% %html_text();
job -job[1:len];company -company[1:len];location -location[1:len];time -time[1:len]# 長度一致 #
data1 -data.frame(job,company,location,time);
if(length(data 0)){
data -na.omit(rbind(data,data1))}
else
{data1 -rep(NA,len);data -na.omit(rbind(data,data1))}
}
}
Sys.sleep(3)# 每隔 3 秒鐘停一次,防止反爬蟲
print(i)
print(sleep end,download start!)
}
data -data[-1,]
write.csv(data,file = filename)
就是這樣了,自己實操一遍才好。
關于 R 語言爬蟲如何爬取招聘網站的招聘信息問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注丸趣 TV 行業資訊頻道了解更多相關知識。