scrapy框架浅谈
554阅读 · 0评论 · 2020/04/26发布 前往评论
Scrapy是一个用于爬网网站并提取结构化数据的应用程序框架。在使用其爬取页面数据的同时还可以存储数据,分布式爬虫,使用平台控制等。十分好用
#安装流程 pip install scrapy #在所需目录下创建爬虫项目 scrapy startproject 项目名称 #创建爬虫文件 scrapy genspider 文件名称 域名
所呈现的界面是这样的
项目名 |—— 项目名 | |—— _init_.py | |—— items.py #数据模型定义 | |—— middlewares.py #中间件定义 | |—— pipelines.py #管道定义 | |—— settings.py #配置文件。 | |—— spider #文件夹 | |—— _init_.py #默认文件 | |—— 项目名.py |——— scrapy.cfg #运行配置文件。
从制作制作爬虫的项目名.py文件写爬虫代码,在Item.py编写代码,最后存储内容在pipelines.py编写
项目名.py
import scrapy import re import os from urllib.parse import urljoin from bloomfilter import Bloomfilter # .当前文件所咋文件夹 # ..当前文件夹所在的文件夹 from ..items import DujiaItem,BlogItem,UserItem class DujiaSpider(scrapy.Spider): name = 'dujia' #爬虫名 allowed_domains = ['toutiao.io'] #允许爬虫搜索的域名范围 start_urls = [*********] # 爬虫网址 custom_settings = {******}#配置相关网页爬取等设置 def parse(self, response): ```当前文start_urls能获得网页解析的时候 yield scrapy.Request( url=response.url, #网址 callback=self.parse_all_page, #指定爬虫下一个函数 dont_filter=True,#scrapy会对request的URL去重 meta={} #传递到下一层的数据 ) def parse_all_page(self,ressponse): pass
存储需要的数据
衔接上面在项目名.py中
from ..items import DujiaItem def parse_all_page(self,ressponse): dujia_list = response.xpath("//ul[@class='subjects']/li") for dujia in dujia_list: dujia_title = dujia.xpath("div/h4/a/@title").extract_first() #获取数据 dujia_href = dujia.xpath("div/h4/a/@href").extract_first() item = DujiaItem() item['dujia_img_src'] = dujia_img_src item['dujia_title'] = dujia_title yield item
在item.py文件中
class DujiaItem(scrapy.Item): # define the f# ields for your item here like: # name = scrapy.Field() dujia_img_src=scrapy.Field() dujia_title=scrapy.Field()
存储内容
1、在setting.py文件下设置
FEED_URI = "dujia.json" # 保存文件名 FEED_FORMAT = "json" # 保存文件格式 FEED_EXPORT_ENCODING = 'utf-8' # 保存文件的编
2、通过管道piplines设置
class PreservationPipeline(object): def process_item(self, item, spider): # 先将字符串转为时间戳 newsTime = time.mktime(time.strptime(item['pub_date'], '%Y-%m-%d %H:%M:%S')) # 获取当前时间戳 nowTime = time.time() if (nowTime - newsTime) / (60 * 60) > 1: raise DropItem("%s ,Not Fresh!" % item) # 超过一个小时,丢弃 return item class CleanPipeline(object): """删除掉所有的\r\n符号""" def process_item(self, item, spider): def clear_html(text): html = BeautifulSoup(text) return html.get_text().replace('\n', '') item['desc'] = clear_html(item['desc']) return item class JsonFeedPipeline(object): """存储到指定的Json文件中""" def __init__(self): self.json_file = open('pipResult.json', 'w') self.json_file.write("[\n") def process_item(self, item, spider): line = json.dumps(dict(item)) + ",\n" self.json_file.write(line.encode('utf-8').decode("unicode_escape")) # BeautifulSoup会统一为Unicode编码,需要重新编码一下 return item def close_spider(self, spider): self.json_file.write("\n]") self.json_file.close()
在setting设置
ITEM_PIPELINES = { #运行时间顺序 'chinanews_crawler.pipelines.PreservationPipeline': 500, 'chinanews_crawler.pipelines.CleanPipeline': 501, 'chinanews_crawler.pipelines.JsonFeedPipeline': 502, }