scrapy文档css
一:安装scrapyhtml
a. pip3 install wheelpython
b. 下载twisted http://www.lfd.uci.edu/~gohlke/pythonlibs/#twistedshell
c. 进入下载目录,执行 pip3 install Twisted‑17.1.0‑cp35‑cp35m‑win_amd64.whl数据库
d. pip3 install scrapyjson
e. 下载并安装pywin32:https://sourceforge.net/projects/pywin32/files/app
二:基本操做dom
(1)新建工程:在建立工程以前先进入想用来保存代码的目录,而后执行scrapy
scrapy startproject xxx #建立项目ide
Microsoft Windows [版本 10.0.16299.309] (c) 2017 Microsoft Corporation。保留全部权利。 C:\Users\felix>cd C:\Users\felix\PycharmProjects\scrapy_quotes C:\Users\felix\PycharmProjects\scrapy_quotes>scrapy startproject quotes New Scrapy project 'quotes', using template directory 'c:\\users\\felix\\appdata\\local\\programs\\python\\python36\\lib\\site-packages\\scrapy\\templates\\project', created in: C:\Users\felix\PycharmProjects\scrapy_quotes\quotes You can start your first spider with: cd quotes scrapy genspider example example.com
执行这条命令将建立一个新目录:包括的文件以下:
scrapy.cfg:项目配置文件
quotes/:项目python模块,待会代码将从这里导入
quotes/items:项目items文件
quotes/pipelines.py:项目管道文件
quotes/settings.py:项目配置文件
quotes/spiders:放置spider的目录
(2):建立爬虫
cd quotes # 先进入项目目录
scrapy genspider name name.com # 建立爬虫
scrapy crawl name # 运行爬虫
(3):建立的爬虫类解析
import scrapy from quotes.items import QuotesItem class QuotespiderSpider(scrapy.Spider): name = 'quotespider' # 爬虫名称 allowed_domains = ['quotes.toscrape.com'] # 容许爬虫访问的域名,能够多个 start_urls = ['http://quotes.toscrape.com/'] # 爬虫开始的url地址 def parse(self, response): # 爬虫返回的数据解析函数 quotes = response.css('.quote') # 经过css选择器选择相应的内容 for quote in quotes: item = QuotesItem() # item作数据持久化的 text = quote.css('.text::text').extract_first() # ::text 表示输出文本内容 author = quote.css('.author::text').extract_first() # ::text 表示输出文本内容 tags = quote.css('.tags .tag::text').extract() # extract_first() 表示找第一个,extract()表示找到全部,并返回一个列表 item['text'] = text # 赋值 首先要在items类中建立 item['tags'] = tags item['author'] = author yield item # 生成item 作数据存储 next = response.css('.pager .next a::attr(href)').extract_first() # 获得相对的url url = response.urljoin(next) # 获取一个绝对的url,获取下一页的url yield scrapy.Request(url=url, callback=self.parse) # 处理连接,将返回的response交给callback的回调函数 # scrapy shell quotes.toscrape.com # 进入命令行调试 # scrapy crawl quotes -o quotes.json(.csv .xml) # 数据保存,能够保存多个类型
(4):items类解析
Items是将要装载抓取的数据的容器,它工做方式像python里面的字典,但它提供更多的保护,好比对未定义的字段填充以防止拼写错误。
它经过建立一个scrapy.item.Item类来声明,定义它的属性为scrpy.item.Field对象,就像是一个对象关系映射(ORM).
咱们经过将须要的item模型化,来控制得到的站点数据,好比咱们要得到站点的名字,url和网站描述,咱们定义这三种属性的域。要作到这点,咱们编辑在quotes目录下的items.py文件,咱们的Item类将会是这样
import scrapy class QuotesItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() text=scrapy.Field() #建立文本字段 author=scrapy.Field() # 建立做者字段 tags=scrapy.Field() # 建立标签字段
(5):pipeline类解析
import pymongo from scrapy.exceptions import DropItem # 要使用pipline必定要在设置中指定 class QuotesPipeline(object): def process_item(self, item, spider): return item # 一个pipeline要么返回item 要么返回dropitem class TextPipeline(object): def __init__(self): self.limit = 50 def process_item(self, item, spider):
# 这里的item为item类中的item
# 大于50字的文本进行处理 if item['text']: if len(item['text']) > self.limit: item['text'] = item['text'][0:self.limit].rstrip() + '...' return item else: return DropItem('Missing Text') # 添加数据库的操做 class MongoPipeline(object): def __init__(self, mongo_url, mongo_db):
# 初始化数据库 self.mongo_url = mongo_url self.mongo_db = mongo_db
# 该类方法能够从设置中读取数据 @classmethod def from_crawler(cls, crawler): return cls( # 从设置里面获取数据库的设置信息 mongo_url=crawler.settings.get('MONGO_URL'), mongo_db=crawler.settings.get('MONGO_DB') ) def open_spider(self, spider): # 启动爬虫时作的操做
# 初始化数据库 self.client = pymongo.MongoClient(self.mongo_url) self.db = self.client[self.mongo_db]
# 处理item的方法,必须实现返回item或者dropitem def process_item(self, item, spider): name = item.__class__.__name__ # item的名称 self.db[name].insert(dict(item)) return item def close_spider(self, spider): self.client.close() # 结束爬虫时关闭数据库
(6):运行
scrapy crawl quotespider。