第 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 大三房,低总价,满5v1,精装修可直接拎包入住!!
## 3 此房业主诚意出出售,楼层好 视野宽阔,采光充足
## 4 满五年 品质小区 配套成熟 交通便利
## 5 品质三房,楼层好,配套设施齐全
## 6 满五年+视野好+保养好拎包入住+配套成熟
## houseinfo
## 1 5室3厅 | 196.33平米 | 南 | 精装 | 低楼层(共3层) | 2009年建 | 板楼
## 2 3室2厅 | 137.19平米 | 南 | 简装 | 低楼层(共12层) | 2009年建 | 板楼
## 3 2室2厅 | 88平米 | 南 | 简装 | 高楼层(共4层) | 2009年建 | 板楼
## 4 2室2厅 | 99.33平米 | 南 北 | 精装 | 低楼层(共16层) | 2007年建 | 板楼
## 5 3室2厅 | 115.86平米 | 南 | 简装 | 低楼层(共6层) | 1998年建 | 板楼
## 6 3室2厅 | 116.43平米 | 南 | 简装 | 高楼层(共6层) | 2002年建 | 板楼
## price price_per
## 1 568 28,931元/平
## 2 288 20,993元/平
## 3 262 29,773元/平
## 4 230 23,156元/平
## 5 145 12,516元/平
## 6 269 23,105元/平
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
## <chr> <chr> <dbl> <dbl> <dbl>
## 1 华东 安徽… 28.0 27.8 0.24
## 2 华东 山东… 26.6 26.7 -0.05
## 3 华东 浙江… 29.9 29.8 0.1
## 4 华东 江西… 28.9 28.6 0.33
## 5 华东 福建… 29.1 28.9 0.23
## 6 华东 江苏… 28.0 28.4 -0.38
## # … with 1 more variable: diff_last_week <dbl>
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.45 ymin: 6.319 xmax: 135.1 ymax: 53.56
## 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("全国猪肉价格地图")