利用Java 爬取一个房价数据代码 利用Spring Boot charts图表展出代码
时间: 2023-09-16 13:09:03 浏览: 46
爬取房价数据的代码:
```java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HousePriceCrawler {
public static void main(String[] args) throws IOException {
String url = "https://bj.lianjia.com/ershoufang/pg1/";
List<String> prices = new ArrayList<>();
Connection conn = Jsoup.connect(url);
Document doc = conn.get();
Elements elements = doc.select(".totalPrice");
for (Element e : elements) {
prices.add(e.text());
}
System.out.println(prices);
}
}
```
展示房价数据的代码:
```java
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HousePriceController {
@RequestMapping("/house-price")
public String showHousePrice(Model model) {
List<String> prices = new ArrayList<>();
prices.add("100");
prices.add("200");
prices.add("150");
prices.add("300");
prices.add("250");
model.addAttribute("prices", prices);
return "house-price";
}
}
```
在 resources 目录下创建一个名为 `templates` 的目录,并在其中创建一个名为 `house-price.html` 的文件,其内容如下:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>房价数据</title>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.1.2/echarts.min.js"></script>
</head>
<body>
<div id="chart" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
var prices = [[${prices}]];
var myChart = echarts.init(document.getElementById('chart'));
var option = {
title: {
text: '房价数据'
},
tooltip: {},
xAxis: {
data: ["A", "B", "C", "D", "E"]
},
yAxis: {
type: 'value'
},
series: [{
name: '房价',
type: 'bar',
data: prices
}]
};
myChart.setOption(option);
</script>
</body>
</html>
```
最后,运行 Spring Boot 项目,在浏览器中访问 `http://localhost:8080/house-price`,即可看到房价数据的柱状图。