首先下载scrapy模块

这里有惊喜

https://www.cnblogs.com/bobo-zhang/p/10068997.html

创建一个scrapy文件

首先在终端找到一个文件夹

输入

scrapy startproject jy (项目件名)

修改setting文件配置

# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36' # Obey robots.txt rules
ROBOTSTXT_OBEY = Fals

cd 到 spiders文件,在终端创建一个文件

scrapy genspider myjy(文件名) www.xxx.com

在文件里执行我们的第一个代码吧

#实现解析+持久化存储


# -*- coding: utf-8 -*-
import scrapy class FirstSpider(scrapy.Spider):
#爬虫文件的名称
name = 'first'
#允许的域名
#allowed_domains = ['www.xxx.com']
#起始url列表
start_urls = ['https://www.qiushibaike.com/text/']
#实现了数据的基本解析操作
# def parse(self, response):
# div_list = response.xpath('//div[@id="content-left"]/div')
# for div in div_list:
# #author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
# #如果可以保证xpath返回的列表中只有一个列表元素则可以使用extract_first(),否则必须使用extract()
# author = div.xpath('./div[1]/a[2]/h2/text()').extract_first()
# content = div.xpath('./a[1]/div/span//text()').extract()
# content = ''.join(content)
# print(author,content) #实现解析+持久化存储
#1.基于终端指令的持久化存储
# 只可以将parse方法的返回值持久化存储到本地的文本中
#2.基于管道的持久化存储 # 1.基于终端指令的持久化存储
def parse(self, response):
div_list = response.xpath('//div[@id="content-left"]/div')
all_data = []
for div in div_list:
#author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
#如果可以保证xpath返回的列表中只有一个列表元素则可以使用extract_first(),否则必须使用extract()
author = div.xpath('./div[1]/a[2]/h2/text()').extract_first()
content = div.xpath('./a[1]/div/span//text()').extract()
content = ''.join(content) dic = {
'author':author,
'content':content
} all_data.append(dic) return all_data
 

最后运行文件

scrapy crawl myjy

#解析+管道持久化存储

首先在psrse里写入文件

# -*- coding: utf-8 -*-
import scrapy from bossPro.items import BossproItem
class BossSpider(scrapy.Spider):
name = 'boss'
# allowed_domains = ['www.xxx.com']
start_urls = ['https://www.zhipin.com/job_detail/?query=python%E7%88%AC%E8%99%AB&scity=101010100&industry=&position='] url = 'https://www.zhipin.com/c101010100/?query=python爬虫&page=%d&ka=page-2'
page = 1
#解析+管道持久化存储
def parse(self, response):
li_list = response.xpath('//div[@class="job-list"]/ul/li')
for li in li_list:
job_name = li.xpath('.//div[@class="info-primary"]/h3/a/div/text()').extract_first()
salary = li.xpath('.//div[@class="info-primary"]/h3/a/span/text()').extract_first()
company = li.xpath('.//div[@class="company-text"]/h3/a/text()').extract_first() #实例化一个item对象
item = BossproItem()
#将解析到的数据全部封装到item对象中
item['job_name'] = job_name
item['salary'] = salary
item['company'] = company #将item提交给管道
yield item if self.page <= 3:
print('if 执行!!!')
self.page += 1
new_url = format(self.url%self.page)
print(new_url)
#手动请求发送
yield scrapy.Request(url=new_url,callback=self.parse)

配置items.py文件,用来作为数据结构

import scrapy

class BossproItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
job_name = scrapy.Field()
salary = scrapy.Field()
company = scrapy.Field()

在pipelines.py里写入文件

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymysql
from redis import Redis
class BossproPipeline(object):
fp = None
def open_spider(self, spider):
print('开始爬虫......')
self.fp = open('./boss.txt','w',encoding='utf-8')
def close_spider(self, spider):
print('结束爬虫......')
self.fp.close()
#爬虫文件每向管道提交一次item,则该方法就会被调用一次.
#参数:item 就是管道接收到的item类型对象 def process_item(self, item, spider):
#print(item)
self.fp.write(item['job_name']+':'+item['salary']+':'+item['company']+'\n')
return item #返回给下一个即将被执行的管道类 class mysqlPileLine(object):
conn = None
cursor =None
def open_spider(self,spider):
self.conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='',db='scrapy',charset="utf8")
print(self.conn)
def process_item(self, item, spider):
self.cursor = self.conn.cursor()
# print(item)
#print('insert into boss values ("%s","%s","%s")'%(item['job_name'],item['salary'],item['company']))
try:
print('insert into boss values ("%s","%s","%s")'%(item['job_name'],item['salary'],item['company']))
self.cursor.execute('insert into boss values ("%s","%s","%s")'%(item['job_name'],item['salary'],item['company']))
self.conn.commit()
except Exception as e:
print(e)
self.conn.rollback()
def close_spider(self,spider):
self.conn.close()
self.cursor.close() class redisPileLine(object):
conn = None
def open_spider(self,spider):
self.conn = Redis(host='127.0.0.1',port=6379)
print(self.conn)
def process_item(self, item, spider):
# print(item)
dic = {
'name':item['job_name'],
'salary':item['salary'],
'company':item['company']
}
self.conn.lpush('boss',dic)

别忘了在setting里面配置

ITEM_PIPELINES = {
# 'boss.pipelines.BossPipeline': 300,
'boss.pipelines.redisPipeline': 301,
# 'boss.pipelines.mysqlPipeline': 302,
}

爬虫scrapy模块的更多相关文章

  1. 第三百二十六节,web爬虫,scrapy模块,解决重复ur——自动递归url

    第三百二十六节,web爬虫,scrapy模块,解决重复url——自动递归url 一般抓取过的url不重复抓取,那么就需要记录url,判断当前URL如果在记录里说明已经抓取过了,如果不存在说明没抓取过 ...

  2. 第三百二十五节,web爬虫,scrapy模块标签选择器下载图片,以及正则匹配标签

    第三百二十五节,web爬虫,scrapy模块标签选择器下载图片,以及正则匹配标签 标签选择器对象 HtmlXPathSelector()创建标签选择器对象,参数接收response回调的html对象需 ...

  3. 第三百二十四节,web爬虫,scrapy模块介绍与使用

    第三百二十四节,web爬虫,scrapy模块介绍与使用 Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中.其最初是为了 ...

  4. 第三百二十三节,web爬虫,scrapy模块以及相关依赖模块安装

    第三百二十三节,web爬虫,scrapy模块以及相关依赖模块安装 当前环境python3.5 ,windows10系统 Linux系统安装 在线安装,会自动安装scrapy模块以及相关依赖模块 pip ...

  5. 二 web爬虫,scrapy模块以及相关依赖模块安装

    当前环境python3.5 ,windows10系统 Linux系统安装 在线安装,会自动安装scrapy模块以及相关依赖模块 pip install Scrapy 手动源码安装,比较麻烦要自己手动安 ...

  6. 网页爬虫--scrapy入门

    本篇从实际出发,展示如何用网页爬虫.并介绍一个流行的爬虫框架~ 1. 网页爬虫的过程 所谓网页爬虫,就是模拟浏览器的行为访问网站,从而获得网页信息的程序.正因为是程序,所以获得网页的速度可以轻易超过单 ...

  7. python爬虫scrapy框架——人工识别登录知乎倒立文字验证码和数字英文验证码(2)

    操作环境:python3 在上一文中python爬虫scrapy框架--人工识别知乎登录知乎倒立文字验证码和数字英文验证码(1)我们已经介绍了用Requests库来登录知乎,本文如果看不懂可以先看之前 ...

  8. python爬虫scrapy项目详解(关注、持续更新)

    python爬虫scrapy项目(一) 爬取目标:腾讯招聘网站(起始url:https://hr.tencent.com/position.php?keywords=&tid=0&st ...

  9. 自己动手实现爬虫scrapy框架思路汇总

    这里先简要温习下爬虫实际操作: cd ~/Desktop/spider scrapy startproject lastspider # 创建爬虫工程 cd lastspider/ # 进入工程 sc ...

随机推荐

  1. 并发编程~~~多线程~~~计算密集型 / IO密集型的效率, 多线程实现socket通信

    一 验证计算密集型 / IO密集型的效率 IO密集型: IO密集型: 单个进程的多线程的并发效率高. 计算密集型: 计算密集型: 多进程的并发并行效率高. 二 多线程实现socket通信 服务器端: ...

  2. TensorFlow从1到2(十三)图片风格迁移

    风格迁移 <从锅炉工到AI专家(8)>中我们介绍了一个"图片风格迁移"的例子.因为所引用的作品中使用了TensorFlow 1.x的代码,算法也相对复杂,所以文中没有仔 ...

  3. MVC(基础一)

    MVC学习之前必须掌握的c#基础知识 一.类自动属性 public class Person { //自动属性 public string Name { get; set; } private int ...

  4. 如何在Markdown格式下插入动图/gif

    上传GIF动图与上传普通图片是一样的,都需要以下在markdown语法中 ![]() 的小括号内填写图片的地址.问题在于如何获取本地gif的地址呢? 核心的东西就是要把这个gif动图传上网络,这样图片 ...

  5. 克隆系统后如何重新清除SID

    为什么要清除SID? SID(Security Identifiers,安全标识符)是Windows中标识用户.组和计算机的唯一的号码,Windows操作系统通过SID对计算机和用户进行识别.用户的权 ...

  6. mysql执行操作时卡死

    有时候使用Navicat对mysql数据库进行添加字段,truncate或其他操作时会一直卡住不动,后来查看进程才发现一直处于等待状态 先执行,列出所有进程 show full processlist ...

  7. JS setInterval 循环定时器的使用 以及动态倒计时展示

    例: var setTime = setInterval(function () { ff(); //每秒调用的方法函数 }, 1000); //1000毫秒为1秒 //可使用 clearInterv ...

  8. 如何将Javaweb工程的访问协议由http改为https及通过域名访问?

    将javaweb工程的http访问协议更改为https,需要做一下几部操作: 通过jre生成证书 调整tomcat的配置 调整工程的web.xm配置 具体详细过程如下: 一.生成证书 打开cmd切换到 ...

  9. WPF 使用SetParent嵌套窗口

    有点类似与Winform的MDI窗口. 使用函数为SetParent和MoveWindow(经常配合). [DllImport("user32.dll", SetLastError ...

  10. sqlite3数据库最大可以是多大?可以存放多少数据?读写性能怎么样?

    sqlite是款不错的数据库,使用方便,不需要事先安装软件,事先建表.很多人担心它的性能和数据存储量问题. 比如有的网友问:Sqlite数据库最大可以多大呀?会不会像acc数据库那样,几十MB就暴掉了 ...