scrapy的爬虫流程
创建scrapy项目
创建一个爬虫
完善spider
spider的数据传到pipeline
使用pipeline
简单设置log
logging模块的使用
实现翻页请求
实现翻页请求实例
item的使用
在不同的函数中传递参数,meta的使用
阳光热线数据爬取
程序的debug信息
scrapy shell
setting文件
- 为什么需要配置文件
配置文件存放一些公共的变量(比如数据库的地址,账号密码等)
一般用全大写字母命名变量名
pipeline的使用
mongodb的使用
crawlspider的使用
crawlspider实例
下载中间件
scrapy模拟登陆
- 对于scrapy来说,模拟登陆的方式也有两种
- 直接携带cookie
- 找到发送post请求的url,带上信息,发送请求
- 模拟登陆携带cookie
- cookie过期时间很长,常见于一些不规范的网站
- 能在cookie过去之前把搜有的数据拿取到
- 配合其他程序使用,比如使用selenium把登陆之后的cookie获取到保存本地,scrapy发送请求之前先读取本地cookie
- 设置cookie请求url
cookie不能放到headers中,如果放到headers中的话会请求不到
如何确定知道cookie确实是在不同的解析函数中传递的呢
可以在setting中添加配置COOKIES_DEBUG = True
在启动的时候在终端控制台中就会打印出请求url时,cookie的传递
- 模拟登陆发送post请求
- 模拟登陆自动登录
scrapy_redis
- scrapy_redis:基于url增量爬虫的实现
具体体现在:request去重,爬虫持久化,和轻松实现分布式
- 在setting中的配置
- 当执行爬虫时
- 当我们在setting中关闭Redispipeline,时,观察redis中三个键的存储数据量的变化
- 变化的结果:
- requests有变化(变多或者变少或者不变)
- dupefilter 变多
- items 不变
- 变化结果分析
- Redispipeline中仅仅实现了item数据存储到redis的过程,我们可以新建一个pipeline(或者修改默认的ExamoleOipeline),让数据存储到任意地方
- 变化的结果:
- 当我们在setting中关闭Redispipeline,时,观察redis中三个键的存储数据量的变化
- scrapy_redis源码解析
- Redispipeline
- RFPDupeFilter
- Scheduler
- 总结
分布式爬虫 RedisSpider
创建爬虫的方式都是一样
from scrapy_redis.spiders import RedisSpider
Crontab爬虫定时执行
将数据存储到MySQL
pipelines.py是设置抓取内容存储方式的文件,例如可以存储到mysql或是json文件中,读者可以根据自己实际需求选择相应的方式,本例中选择存储到mysql中。from twisted.enterprise import adbapi import MySQLdb import MySQLdb.cursors from scrapy.crawler import Settings as settings class TestPipeline(object): def __init__(self): dbargs = dict( host = 'your host' , db = 'crawed', user = 'user_name', #replace with you user name passwd = 'user_password', # replace with you password charset = 'utf8', cursorclass = MySQLdb.cursors.DictCursor, use_unicode = True, ) self.dbpool = adbapi.ConnectionPool('MySQLdb',**dbargs) ''' The default pipeline invoke function ''' def process_item(self, item,spider): res = self.dbpool.runInteraction(self.insert_into_table,item) return item def insert_into_table(self,conn,item): conn.execute('insert into zreading(title,author,pub_date,types,tags,view_counts,content) values(%s,%s,%s,%s,%s,%s,%s)', (item['title'],item['author'],item['pub_date'],item['types'],item['tags'],item['view_count'],item['content']))
import pymysql class TenPipeline(object): def __init__(self): # 创建连接 self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db="suning") # 创建游标 self.cursor = self.conn.cursor() def process_item(self, item, spider): res = self.insert_into_table(item) return item def insert_into_table(self,item): data = [(item["title"],item["position_type"],item["count"],item["addr"],item["publish_date"])] self.cursor.executemany("insert into tm_position (title,position_type,count,addr,publish_date)values(%s,%s,%s,%s,%s)",data) self.conn.commit()
- Redispipeline