【发布时间】:2016-05-01 06:00:37
【问题描述】:
此代码从此处http://www.bls.gov/schedule/news_release/2015_sched.htm 抓取每个包含“发布”列下的就业情况的日期。
pg <- read_html("http://www.bls.gov/schedule/news_release/2015_sched.htm")
# 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!
nfpdates2015 <- as.Date(trimws(html_text(es_nodes)), format="%A, %B %d, %Y")
###thanks @hrbrmstr for this###
我想对包含其他年份的其他 URL 重复这一点,以相同的方式命名,仅更改年份编号。特别是对于以下 URL:
#From 2008 to 2015
http://www.bls.gov/schedule/news_release/2015_sched.htm
http://www.bls.gov/schedule/news_release/2014_sched.htm
...
http://www.bls.gov/schedule/news_release/2008_sched.htm
我对@987654324@、HTML 和XML 的了解几乎不存在。我想用 for 循环应用相同的代码,但我的努力是徒劳的。当然,我可以将 2015 年的代码重复八次以获得所有年份,既不会花费太多时间,也不会占用太多空间。然而,我很想知道如何以更有效的方式做到这一点。谢谢。
【问题讨论】:
标签: html r for-loop web-scraping lapply