流程
环境配置
python2.7
scrapy
lxml
pymysql
mysql8.0
分析网页
chrome浏览器,F12开发人员工具,查看要爬取的元素标签的标志。
这里要爬取的内容包括用户发布的内容,小区名,小区地址,房子大小,几室几厅,几层,朝向,建筑年代,房价,均价等信息。
查看各个元素标签特征,方便写对应的xpath。
item定义
根据要爬取的信息定义item。
item是scrapy的存储信息的结构,类似于dict。
class SofangSpiderItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
name = scrapy.Field()
page = scrapy.Field()
city = scrapy.Field()
area = scrapy.Field()
address = scrapy.Field()
type_how_big = scrapy.Field()
type_howmany_room = scrapy.Field()
type_which_floor = scrapy.Field()
type_direction = scrapy.Field()
type_time = scrapy.Field()
price = scrapy.Field()
junjia = scrapy.Field()
'''
xpath描述
response.xpath("//div[@class='list_info clearfix']/div[@class='list_l']/div[@class='list list_free']/dl")
该语句定位到这里的dl标签,可以看到每页有25个dl标签,可以for循环处理,收取信息,再进入下一页。
进入下一页
scrapy通过request对网页进行下载再爬取,通过xpath锁定下一页标签对应的,href属性,发起请求,爬取下一页信息。
next_page = response.xpath("//li[@class='right']/a[@class='page']/@href").extract()
爬取信息存储
信息存储在mysql数据库,详见另一篇博客。
问题
导包问题
在pycharm下开发,始终找不到item.py文件。
解决方法:
将外层设为根目录,这样可以保证pycharm中没有错误,但在命令行里运行scrapy crawl 还是会报NO Moudle name “items”。
将from items import WebcrawlerScrapyItem改为
from ..items import WebcrawlerScrapyItem
“..”表示在上一级目录下找
解决。
cite: https://blog.csdn.net/Haihao_micro/article/details/78529370
中文编码问题
python2默认用ascii,程序中不能包含乃至输出中文,如果有中文会提示报错,
所以要声明编码
# coding:utf-8
此时,中文编码为utf-8,但print的时候会变成乱码,因为python2把数据读到内存中会使用’unicode’编码,原来的utf-8编码就乱了。如果用unicode就能正常显示
n = unicode(n,'utf-8') # utf-8转unicode
print(n)
print(type(n)) # unicode
如果unicode要转成utf-8就用encode
n = n.encode('utf-8')