文章目录
前言
记录scrapy基础(通过链家案例)
一、scrapy文件
1.文件介绍
1.item : 定制你要抓取的字段(比方说你要去爬取一个网站 里面有标题 用name变量去接收 就先在item里面定制好接收的字段)
2.setting:放的是你爬虫的最基本信息(包括爬虫的初始化伪装 也需要在这里面去完成)
3.pipelines: 保存数据(不管你是要保存数据到Excel里面或者数据里面都需要在这个文件抒写)
4.middlewares: 爬虫中间件
5.spiders下的爬虫文件:是我们核心的文件,用来爬取数据,分析数据的文件
6.start: 调用爬虫(运行scrapy有三种方法(仅限于本人认知,有其他方法可以私信我,共同进步,谢谢),后面有解释)
2.start.py文件的创建
from scrapy import cmdline
cmdline.execute(['scrapy','crawl','wangyi(爬虫名字)','--nolog(消除日志)'])
#每次只要改爬虫名字就ok
二、scrapy的创建
前提:路径切换 cd
需要cd到你准备放scrapy的文件下
1. 创建scrapy项目
scrapy startproject 项目名
例:scrapy startproject spider
2.1 先cd到路径(2.1,2.2 在创建完scrapy项目后有提示)
cd 项目名
例:cd spider
2.2 创建爬虫程序
scrapy genspider example example.com
scrapy genspider:固定的
example:爬虫的名字(不固定的) 不能和项目名一样
example.com:允许爬取的域名
例: scrapy genspider wnagyi 163.com
三.通过案例介绍scrapy(链家)
1.修改settings
1.修改U_A
2.注释robts协议或将值改为False
3.开启管道类(开启后才能保存)
2.对lianjia.py(爬虫文件)进行操作
class LianjiaSpider(scrapy.Spider):
name = "lianjia" # 爬虫名字
allowed_domains = ["lianjia.com"] # 允许爬取的域名范围
start_urls = ["https://nb.lianjia.com/ershoufang/rs/"] # 起始url
def parse(self, response):
hrefs = response.xpath('//div[@class="title"]/a/@href').extract()
titles = response.xpath('//div[@class="title"]/a/text()').extract()
houseinfos = response.xpath('//div[@class="houseInfo"]/text()').extract()
prices = response.xpath('//div[@class="totalPrice totalPrice2"]/span/text()').extract()
for href, title, houseinfo, price in zip(hrefs, titles, houseinfos, prices):
print(href)
print(title)
print(houseinfo)
print(price + '万')
print('----' * 10)
.extract – 提取内容
3.scrapy shell的使用(测试语法是否正确)
一次一次运行时间较长,可以通过scrapy shell去确认爬虫中写的xpath语法是否正确
打开cmd终端,进入到Scrapy项目所在目录,进入到Scrapy框架所在的环境中,输入命令:scrapy shell url ,就会进入到scrapy的shell环境中,在这个环境中,你可以跟在爬虫的parse方法中一样使用了
例: cd mySpider 进入项目路径
scrapy shell "https://nb.lianjia.com/ershoufang/rs/" #想要测试的url
hrefs = response.xpath('//div[@class="title"]/a/@href').extract()
print(hrefs)
4.定义数据存储模型(items.py)
class MyspiderItem(scrapy.Item):
# 实际是一个模板类(数据建模) 事先定义好你要爬取的字段
title = scrapy.Field() # 标题
href = scrapy.Field() # 链接
houseinfo = scrapy.Field() # 室内介绍
price = scrapy.Field() # 价格
5.将数据打包并返回给引擎 (先导入类)
import scrapy
# 导入类
from myspider.items import MyspiderItem
class LianjiaSpider(scrapy.Spider):
name = "lianjia" # 爬虫名字
allowed_domains = ["lianjia.com"] # 允许爬取的域名范围
start_urls = ["https://nb.lianjia.com/ershoufang/rs/"] # 起始url
def parse(self, response):
hrefs = response.xpath('//div[@class="title"]/a/@href').extract()
titles = response.xpath('//div[@class="title"]/a/text()').extract()
houseinfos = response.xpath('//div[@class="houseInfo"]/text()').extract()
prices = response.xpath('//div[@class="totalPrice totalPrice2"]/span/text()').extract()
for href, title, houseinfo, price in zip(hrefs, titles, houseinfos, prices):
print(href)
print(title)
print(houseinfo)
print(price + '万')
print('----' * 10)
# 将数据打包 实例化类
item = MyspiderItem()
item['href'] = href
item['title'] = title
item['houseinfo'] = houseinfo
item['price'] = price
# 将数据返回给引擎
yield item
6.保存数据(pipelines.py)
import json
class MyspiderPipeline:
def __init__(self):
self.file = open('linajiao.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
print(type(item)) # <class 'myspider.items.MyspiderItem'>
dict_data = dict(item)
print(type(dict_data)) # <class 'dict'>
json_data = json.dumps(dict_data, ensure_ascii=False) + '\n' # ensure_ascii=False不要让数据编程编码
self.file.write(json_data) # 写入json数据
return item
def __del__(self): # 用完之后关闭文件
self.file.close()
7.scrapy文件的运行
1.命令运行
命令:在项目目录下执行scrapy crawl <爬虫名字>
scrapy crawl 爬虫名字 --nolog 忽略日志信息
2.创建start.py文件
from scrapy import cmdline
cmdline.execute(['scrapy','crawl','wangyi(爬虫名字)','--nolog(忽略日志)'])
#每次只要改爬虫名字就ok
3.spiders下的爬虫文件中运行(代码与2中一样)
总结
记录了一些scrapy基础