forked from perlatex/R_for_Data_Science
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rvest.Rmd
112 lines (73 loc) · 1.96 KB
/
rvest.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# 网络爬虫 {#rvest}
```{r message = FALSE, warning = FALSE}
library(tidyverse)
library(rvest)
library(sf)
```
## 链家网
```{r}
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)
}
```
```{r}
tb <- urls %>% map_df(scrape_house_info)
tb
```
## 猪肉价格
```{r}
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
```
```{r}
china <- st_read("./demo_data/chinamap_data/bou2_4p.shp") %>%
st_set_crs(4326) %>%
group_by(NAME) %>%
summarize()
```
```{r}
china_uni <- china %>%
mutate( NAME = iconv(NAME, "GBK", "UTF-8") ) %>%
mutate_at(vars(NAME), ~str_remove_all(., "自治区|回族|维吾尔|壮族") ) %>%
mutate_at(vars(NAME), ~str_trim(.))
```
```{r}
df <- left_join(china_uni, df_price, by = c("NAME" = "name"))
```
```{r,fig.width= 8, fig.height= 8}
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("全国猪肉价格地图")
```