一.创建项目
scrapy startproject putu
二.创建spider文件
scrapy genspider patubole patubole.com
![](https://upload-images.jianshu.io/upload_images/13406307-2b466e50d1466449.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
三.利用chrome浏览器分析出房价和标题的两个字段的xpath表达式,开始编写patubole.py文件。网络的爬取是通过这个文件进行的
以下代码是最终的代码
所建的patubole.py文件必须实现name,parse函数,start_url这三个属性
![](https://upload-images.jianshu.io/upload_images/13406307-2bcc1d0096ed5677.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
四.将爬取的数据保存到数据库sufang中。
(1)在pycharm中新建数据库
![](https://upload-images.jianshu.io/upload_images/13406307-b6ee56728b371de2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/13406307-c96232095c30e3a0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
完成后会出现
![](https://upload-images.jianshu.io/upload_images/13406307-d1aca7a940ced872.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
(2)将数据存放在新建的数据库zufang的数据表sufang中
数据的爬取是有patubole.py实现的,数据的存储是由pipelines.py实现的,pipelines.py又是有items.py提供数据的支持
所以编写items.py
![](https://upload-images.jianshu.io/upload_images/13406307-486195c922665735.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
此时就要回过头来修改刚开是为了测试编写的patubole.py 文件
代码如下
![](https://upload-images.jianshu.io/upload_images/13406307-84eb8025ebc965b0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
3)在settings.py中进行PatuPipeline文件配置
ITEM_PIPELINES = {
'patu.pipelines.PatuPipeline': 300,
}
(5)pipelines.py文件代码,实现存储数据到数据库中
其中包含SQL的相关知识
![](https://upload-images.jianshu.io/upload_images/13406307-7e6ac6fadb62c5d4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
最终结果
![](https://upload-images.jianshu.io/upload_images/13406307-0e466bace6b10231.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
其中main.py文件是为了调式方便而添加的,可以不用,直接用相关命令启动爬虫
![](https://upload-images.jianshu.io/upload_images/13406307-04baf23f99c07649.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)