我们计划抓取的数据:杭州的天气信息
实现数据抓取的逻辑:使用python 请求 URL,会返回对应的 HTML 信息,我们解析 html,获得自己需要的数据。(很简单的逻辑)
第一步:创建 Python 文件

写第一段Python代码

这段代码类似于 Java 中的 Main 方法。可以直接鼠标右键,选择 Run。

第二步:请求RUL
python 的强大之处就在于它有大量的模块(类似于Java 的 jar 包)可以直接拿来使用。
我们需要安装一个 request 模块: File - Setting - Product - Product Interpreter


点击如上图的 + 号,就可以安装 Python 模块了。搜索 requests 模块(有 s 噢),点击 Install。

我们顺便再安装一个beautifulSoup4 和 pymysql模块,beautifulSoup4 模块是用来解析 html 的,可以对象化 HTML 字符串。pymysql 模块是用来连接 mysql 数据库使用的。


相关的模块都安装之后,就可以开心的敲代码了。
定义一个 getContent 方法:

在 main 方法中调用:

第三步:分析页面数据
定义一个 getData 方法:

上面的解析其实就是按照 HTML 的规则解析的。可以打开杭州天气在开发者模式中(F12),看一下页面的元素分布。

在 main 方法中调用:

数据写入excel
现在我们已经在 Python 中拿到了想要的数据,对于这些数据我们可以先存放起来,比如把数据写入 csv 中。
定义一个 writeDate 方法:

在 main 方法中调用:

执行之后呢,再指定路径下就会多出一个 weather.csv文件,可以打开看一下内容。


到这里最简单的数据抓取--储存就完成了。
网友评论