第二十三章 scrapy_redis讲解
1. python和redis的交互
首先安装redis,pip install redis。
Collecting redis
Downloading redis-3.5.3-py2.py3-none-any.whl (72 kB)
|████████████████████████████████| 72 kB 207 kB/s
Installing collected packages: redis
Successfully installed redis-3.5.3
在pycharm里新建一个py文件redis_crawl.py
然后是连接redis,需要连接的地址和端口号
我们可以定义一个类,在初始化方法里面定义连接方法。
import redis # 首先导入redis模块
class StringRedis():
def __init__(self):
# 连接redis
self.r = redis.StrictRedis(host='127.0.0.1',port=6379)
# 定义set方法
def string_set(self,k,v):
res = self.r.set(k,v)
print(res)
if __name__ == '__main__':
s = StringRedis()
s.string_set('name','Jerry777')
我们运行一下:
conn = self.connection or pool.get_connection(command_name, **options)
File "D:\Python38\lib\site-packages\redis\connection.py", line 1192, in get_connection
connection.connect()
File "D:\Python38\lib\site-packages\redis\connection.py", line 563, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error 10061 connecting to 127.0.0.1:6379. 由于目标计算机积极拒绝,无法连接。.
结果报了个错,我刚才把Redis服务关闭了,这里需要重新打开:
D:\Download\redis-latest>cd redis-latest
D:\Download\redis-latest\redis-latest>redis-server.exe
[14424] 11 Mar 14:47:45.200 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server.exe /path/to/redis.conf
_._
_.-``__ ''-._
_.-`` `. `_. ''-._ Redis 3.0.503 (00000000/0) 64 bit
.-`` .-```. ```\/ _.,_ ''-._
( ' , .-` | `, ) Running in standalone mode
|`-._`-...-` __...-.``-._|'` _.-'| Port: 6379
| `-._ `._ / _.-' | PID: 14424
`-._ `-._ `-./ _.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' | http://redis.io
`-._ `-._`-.__.-'_.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' |
`-._ `-._`-.__.-'_.-' _.-'
`-._ `-.__.-' _.-'
`-._ _.-'