2016-05-01 7 views
2

リリース欄のEmployment Situationを含む日付はすべて、http://www.bls.gov/schedule/news_release/2015_sched.htmここからウェブスクレイプする必要があります。 Web廃棄の出力は次のようになります。日付と文字列によるテーブルからのWebスクラップR

Friday, January 09, 2015 
Friday, February 06, 2015 
Friday, March 06, 2015 
Friday, April 03, 2015 
Friday, May 08, 2015 
Friday, June 05, 2015 
Thursday, July 02, 2015 
Friday, August 07, 2015 
Friday, September 04, 2015 
Friday, October 02, 2015 
Friday, November 06, 2015 
Friday, December 04, 2015 

これを実現するには、次のようなことを12回、毎月1回繰り返すと考えました。注http://www.bls.gov/schedule/news_release/2015_sched.htmには、月ごとに1つずつ、tbl2[[2]]tbl3[[3]]という12個のテーブルがあります。

library(rvest) 
url <- 'http://www.bls.gov/schedule/news_release/2015_sched.htm' 
ses <- html_session(url) 
tbl <- html_table(ses, fill = T) 
nfpdates <- tbl[[2]]$`Date` 
nfpdates <- gsub('\\.', '', nfpdates) 
nfpdates <- as.Date(nfpdates, 'weekdaystr(iD,:), %b %d, %Y') 

動作しません。最初の問題は簡単です:私は曜日を参照する方法を知らない:'weekdaystr(iD,:)が間違っています。 2番目はもっと複雑です:「リリース」の下に「雇用状況」を含むテキストのみを抽出する方法は?

ご協力いただければ幸いです。ありがとうございました。

答えて

3

XPathの完璧な使用例:

library(rvest) 

pg <- read_html("http://www.bls.gov/schedule/news_release/2015_sched.htm") 

# we need to target only the <td> elements under the bodytext div 
body <- html_nodes(pg, "div#bodytext") 

# we use this new set of nodes and a relative XPath to get the initial <td> elements, then get their siblings 
es_nodes <- html_nodes(body, xpath=".//td[contains(., 'Employment Situation for')]/../td[1]") 

# clean up the cruft and make our dates! 
as.Date(trimws(html_text(es_nodes)), format="%A, %B %d, %Y") 

## [1] "2015-01-09" "2015-02-06" "2015-03-06" "2015-03-18" "2015-04-03" 
## [6] "2015-05-08" "2015-06-05" "2015-07-02" "2015-08-07" "2015-09-04" 
## [11] "2015-10-02" "2015-11-06" "2015-12-04" 
2

限り最初の問題が関係しているとして、それはこのフォーマットを使用することによって解決することができます。

nfpdates <- as.Date(nfpdates,"%A, %B %d, %Y") 

weekdays()機能を使用して、あなたは曜日を見つけることができます。第二の問題に来て今

、することによって行うことができ、あなたは「雇用状況は」「リリース」列の下に存在しているため、日付を抽出している

を想定した:これは

test <- tbl[[2]]$Date 

test[grepl('Employment Situation',tbl[[2]]$Release)] 
+0

ありがとう! ''%A、%B%d、%Y "'の大文字と小文字の違いはありますか? – Krug

+1

@Gracosはい。形式についての概要を知りたい場合は?strptimeを参照することができます。 –