一、基础学习
- scrapy框架
介绍:大而全的爬虫组件。 安装:
- Win:
下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted pip3 install wheel
pip install Twisted‑18.4.‑cp36‑cp36m‑win_amd64.whl pip3 install pywin32 pip3 install scrapy
- Linux:
pip3 install scrapy 使用:
Django:
# 创建project
django-admin startproject mysite cd mysite # 创建app
python manage.py startapp app01
python manage.py startapp app02 # 启动项目
python manage.runserver Scrapy:
# 创建project
scrapy startproject xdb cd xdb # 创建爬虫
scrapy genspider chouti chouti.com
scrapy genspider cnblogs cnblogs.com # 启动爬虫
scrapy crawl chouti . 创建project
scrapy startproject 项目名称 项目名称
项目名称/
- spiders # 爬虫文件
- chouti.py
- cnblgos.py
....
- items.py # 持久化
- pipelines # 持久化
- middlewares.py # 中间件
- settings.py # 配置文件(爬虫)
scrapy.cfg # 配置文件(部署) . 创建爬虫
cd 项目名称 scrapy genspider chouti chouti.com
scrapy genspider cnblgos cnblgos.com . 启动爬虫
scrapy crawl chouti
scrapy crawl chouti --nolog 总结:
- HTML解析:xpath
- 再次发起请求:yield Request对象

二、eg:爬取抽屉

# -*- coding: utf- -*-
import scrapy
from scrapy.http.response.html import HtmlResponse
# import sys,os,io
# sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') class ChoutiSpider(scrapy.Spider):
name = 'chouti'
allowed_domains = ['chouti.com']
start_urls = ['http://chouti.com/'] def parse(self, response):
# print(response,type(response)) # 对象
# print(response.text)
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text,'html.parser')
content_list = soup.find('div',attrs={'id':'content-list'})
"""
# 去子孙中找div并且id=content-list
f = open('news.log', mode='a+')
item_list = response.xpath('//div[@id="content-list"]/div[@class="item"]')
for item in item_list:
text = item.xpath('.//a/text()').extract_first()
href = item.xpath('.//a/@href').extract_first()
print(href,text.strip())
f.write(href+'\n')
f.close() page_list = response.xpath('//div[@id="dig_lcpage"]//a/@href').extract()
for page in page_list:
from scrapy.http import Request
page = "https://dig.chouti.com" + page
yield Request(url=page,callback=self.parse) # https://dig.chouti.com/all/hot/recent/2

三、知识点

    第一部分:scrapy框架
. scrapy依赖twisted
内部基于事件循环的机制实现爬虫的并发。
原来的你:
url_list = ['http://www.baidu.com','http://www.baidu.com','http://www.baidu.com',] for item in url_list:
response = requests.get(item)
print(response.text) 现在:
from twisted.web.client import getPage, defer
from twisted.internet import reactor # 第一部分:代理开始接收任务
def callback(contents):
print(contents) deferred_list = [] # [(龙泰,贝贝),(刘淞,宝件套),(呼呼,东北)]
url_list = ['http://www.bing.com', 'https://segmentfault.com/','https://stackoverflow.com/' ]
for url in url_list:
deferred = getPage(bytes(url, encoding='utf8')) # (我,要谁)
deferred.addCallback(callback)
deferred_list.append(deferred) # # 第二部分:代理执行完任务后,停止
dlist = defer.DeferredList(deferred_list) def all_done(arg):
reactor.stop() dlist.addBoth(all_done) # 第三部分:代理开始去处理吧
reactor.run() . scrapy
命令:
scrapy startproject xx
cd xx
scrapy genspider chouti chouti.com scrapy crawl chouti --nolog 编写:
def parse(self,response):
# .响应
# response封装了响应相关的所有数据:
- response.text
- response.encoding
- response.body
- response.request # 当前响应是由那个请求发起;请求中 封装(要访问的url,下载完成之后执行那个函数)
# . 解析
# response.xpath('//div[@href="x1"]/a').extract_first()
# response.xpath('//div[@href="x1"]/a').extract()
# response.xpath('//div[@href="x1"]/a/text()').extract()
# response.xpath('//div[@href="x1"]/a/@href').extract()
# tag_list = response.xpath('//div[@href="x1"]/a')
for tag in tag_list:
tag.xpath('.//p/text()').extract_first() # . 再次发起请求
# yield Request(url='xxxx',callback=self.parse)

四、持久化

今日内容:scrapy
- 持久化 pipeline/items - 去重 - cookie - 组件流程:
- 下载中间件 - 深度 内容详细: . 持久化
目前缺点:
- 无法完成爬虫刚开始:打开连接; 爬虫关闭时:关闭连接;
- 分工明确
pipeline/items
a. 先写pipeline类
class XXXPipeline(object):
def process_item(self, item, spider):
return item b. 写Item类
class XdbItem(scrapy.Item):
href = scrapy.Field()
title = scrapy.Field() c. 配置
ITEM_PIPELINES = {
'xdb.pipelines.XdbPipeline': ,
} d. 爬虫,yield每执行一次,process_item就调用一次。 yield Item对象 编写pipeline:
from scrapy.exceptions import DropItem class FilePipeline(object): def __init__(self,path):
self.f = None
self.path = path @classmethod
def from_crawler(cls, crawler):
"""
初始化时候,用于创建pipeline对象
:param crawler:
:return:
"""
print('File.from_crawler')
path = crawler.settings.get('HREF_FILE_PATH')
return cls(path) def open_spider(self,spider):
"""
爬虫开始执行时,调用
:param spider:
:return:
"""
print('File.open_spider')
self.f = open(self.path,'a+') def process_item(self, item, spider):
# f = open('xx.log','a+')
# f.write(item['href']+'\n')
# f.close()
print('File',item['href'])
self.f.write(item['href']+'\n') # return item # 交给下一个pipeline的process_item方法
raise DropItem()# 后续的 pipeline的process_item方法不再执行 def close_spider(self,spider):
"""
爬虫关闭时,被调用
:param spider:
:return:
"""
print('File.close_spider')
self.f.close() 注意:pipeline是所有爬虫公用,如果想要给某个爬虫定制需要使用spider参数自己进行处理。

scrapy框架学习之路的更多相关文章

  1. 自己的Scrapy框架学习之路

    开始自己的Scrapy 框架学习之路. 一.Scrapy安装介绍 参考网上资料,先进行安装 使用pip来安装Scrapy 在开始菜单打开cmd命令行窗口执行如下命令即可 pip install Scr ...

  2. 【SpringCloud之pigx框架学习之路 】2.部署环境

    [SpringCloud之pigx框架学习之路 ]1.基础环境安装 [SpringCloud之pigx框架学习之路 ]2.部署环境 1.下载代码 git clone https://git.pig4c ...

  3. 【SpringCloud之pigx框架学习之路 】1.基础环境安装

    [SpringCloud之pigx框架学习之路 ]1.基础环境安装 [SpringCloud之pigx框架学习之路 ]2.部署环境 1.Cmder.exe安装 (1) windows常用命令行工具 下 ...

  4. go server框架学习之路 - 写一个自己的go框架

    go server框架学习之路 - 写一个自己的go框架 用简单的代码实现一个go框架 代码地址: https://github.com/cw731/gcw 1 创建一个简单的框架 代码 packag ...

  5. Scrapy框架学习 - 使用内置的ImagesPipeline下载图片

    需求分析需求:爬取斗鱼主播图片,并下载到本地 思路: 使用Fiddler抓包工具,抓取斗鱼手机APP中的接口使用Scrapy框架的ImagesPipeline实现图片下载ImagesPipeline实 ...

  6. Scrapy框架学习笔记

    1.Scrapy简介 Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛. 框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网 ...

  7. Scrapy框架学习(一)Scrapy框架介绍

    Scrapy框架的架构图如上. Scrapy中的数据流由引擎控制,数据流的过程如下: 1.Engine打开一个网站,找到处理该网站的Spider,并向该Spider请求第一个要爬取得URL. 2.En ...

  8. scrapy框架学习

    一.初窥Scrapy Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中. 其最初是为了 页面抓取 (更确切来说, 网 ...

  9. Scrapy框架学习参考资料

    00.Python网络爬虫第三弹<爬取get请求的页面数据> 01.jupyter环境安装 02.Python网络爬虫第二弹<http和https协议> 03.Python网络 ...

随机推荐

  1. ci框架多语言切换

    1.多语言切换首先配置config文件默认语言 2.创建自己的语言包:language chinese english目录下的语言包文件名必须以  xx_lang.php 可根据自己的需求创建数组: ...

  2. Java Web(四) 过滤器Filter

    Filter概述 Filter意为滤镜或者过滤器,用于在Servlet之外对request或者response进行修改.Filter提出了过滤链的概念.一个FilterChain包括多个Filter. ...

  3. mysql存储过程中使用游标

    用户变量一般以@开头,作用于全局范围 局部变量需用 declare 定义格式为 declare 变量名 数据类型 [default value]; mysql 数据类型有 int ,float,dat ...

  4. python 定义class时的内置方法

    __contains__():对类实例使用in ,not in操作时调用 class A(object): def __init__(self,num): self.num=num def __con ...

  5. Cracking The Coding Interview 4.7_暂存

    //原文: // // You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds ...

  6. 1.4socket服务器打印信息的四种不同方式()

    方式一 socker 服务器 # -*- coding: utf-8 -*- import sys,os,multiprocessing from socket import * serverHost ...

  7. 打开和写入word文档

    一. 使用win32读取word内容 # -*- coding: utf-8 -*- from win32com import client as wc def readDocx2(): word = ...

  8. 使用DLL在进程间共享数据

    0x01 DLL在进程间共享数据理论 1.可以在Dll中使用#pragma data_seg建立共享类型的数据段将需要共享的数据分离出来,放置在一个独立的数据段里,并把该段的属性设置为共享,从而实现不 ...

  9. 《图解HTTP》读书笔记(转)

    reference:https://www.cnblogs.com/edisonchou/p/6013450.html   目前国内讲解HTTP协议的书是在太少了,记忆中有两本被誉为经典的书<H ...

  10. htmlayout 最简单的实践,用于理解实现原理。

    / testHtmlayout.cpp : 定义应用程序的入口点. // #include "stdafx.h" #include "testHtmlayout.h&qu ...