第 87 章 网络爬虫
大神说rvest 马上推出1.0版本了。
87.1 链家网
urls <- paste0("https://sh.lianjia.com/ershoufang/pg", seq_along(1:2))
scrape_house_info <- function(url) {
web <- read_html(url)
title <- web %>%
html_nodes('.clear .title a') %>%
html_text()
houseinfo <- web %>%
html_nodes('.houseInfo') %>%
html_text()
price <- web %>%
html_nodes('.totalPrice span') %>%
html_text()
price_per <- web %>%
html_nodes('.unitPrice span') %>%
html_text()
df <- data.frame(title, houseinfo, price, price_per)
return(df)
}
## title
## 1 满五视野开阔有车位业主诚意出售
## 2 南、北适合一家三口,进九亭地铁站,诚意出售
## 3 9号线地铁口 公园旁 精装大两房 户型方正 拎包入住
## 4 仁恒滨江次次顶楼高区,精装修自住保养,有段江景
## 5 联排别墅 精装修 大露台 看房随时 诚意出售
## 6 元宝户型 视野好 有钥匙随时看快咨询 万源城快出四房
## houseinfo price
## 1 3室1厅 | 118.15平米 | 南 | 精装 | 高楼层(共22层) | 2015年建 | 板楼 459
## 2 1室2厅 | 68.14平米 | 南 北 | 精装 | 低楼层(共11层) | 2008年建 | 板楼 339
## 3 2室1厅 | 59.48平米 | 南 北 | 精装 | 低楼层(共6层) | 1994年建 | 板楼 385
## 4 3室2厅 | 168.62平米 | 东 北 | 精装 | 31层 | 2001年建 | 板塔结合 2260
## 5 6室2厅 | 227.45平米 | 南 | 精装 | 3层 | 2011年建 | 板楼 | 联排别墅 410
## 6 4室2厅 | 171.2平米 | 南 | 精装 | 高楼层(共24层) | 2008年建 | 板楼 1828
## price_per
## 1 38,849元/平
## 2 49,751元/平
## 3 64,728元/平
## 4 134,030元/平
## 5 18,026元/平
## 6 106,776元/平
87.2 猪肉价格
df_price <-
read_html("https://hangqing.zhuwang.cc/shengzhu/20190905/407978.html") %>%
html_node(".tabzj") %>%
html_table(header = T) %>%
set_names(
c("region", "name", "price_today", "price_yestoday", "diff_last_day", "diff_last_week")
) %>%
mutate_at(vars(name), ~str_remove_all(., " ") ) %>%
mutate_at(vars(name), ~if_else( name == "黑龙江", "黑龙江省", .))
df_price %>%
head()
## # A tibble: 6 × 6
## region name price_today price_yestoday diff_last_day diff_last_week
## <chr> <chr> <dbl> <dbl> <dbl> <dbl>
## 1 华东 安徽省 28.0 27.8 0.24 0.37
## 2 华东 山东省 26.6 26.7 -0.05 0.83
## 3 华东 浙江省 29.9 29.8 0.1 1.84
## 4 华东 江西省 28.9 28.6 0.33 0.4
## 5 华东 福建省 29.1 28.9 0.23 0.52
## 6 华东 江苏省 28.0 28.4 -0.38 0.88
china <- st_read("./demo_data/chinamap_data/bou2_4p.shp") %>%
st_set_crs(4326) %>%
group_by(NAME) %>%
summarize()
## Reading layer `bou2_4p' from data source
## `E:\R_for_Data_Science\demo_data\chinamap_data\bou2_4p.shp'
## using driver `ESRI Shapefile'
## Simple feature collection with 925 features and 7 fields
## Geometry type: POLYGON
## Dimension: XY
## Bounding box: xmin: 73.44696 ymin: 6.318641 xmax: 135.0858 ymax: 53.55793
## CRS: NA
china_uni <- china %>%
mutate( NAME = iconv(NAME, "GBK", "UTF-8") ) %>%
mutate_at(vars(NAME), ~str_remove_all(., "自治区|回族|维吾尔|壮族") ) %>%
mutate_at(vars(NAME), ~str_trim(.))
ggplot(data = df) +
geom_sf( aes(fill = price_today < 28), show.legend = FALSE) +
geom_sf_text(aes(label = NAME),
size = 3
) +
geom_sf_text(aes(label = price_today),
size = 3,
#nudge_x = c(-0.4, 0.5, 0.7),
nudge_y = c(-1, -1, -1)
) +
coord_sf(crs = 4326) +
ggtitle("全国猪肉价格地图")