付费代理IP——Redis数据库的使用01

1.Redis初尝试:

在完成Redis数据库安装后,启动Redis数据库,打开Redis Desktop Manager;
用Python连接数据库

r = redis.Redis(host='127.0.0.1', port=6379, db=1, decode_responses=True)  # 尽量别使用db0

host:Redis数据库地址
port:Redis数据库端口
db:Redis数据库第几数据库,尽量别使用db0数据库
decode_responses:规定Redis数据库数据出数据库的格式,True的话进出都是字符串;False,进出全都是二进制

  1. 字符串操作:String
    Redis中存储String类型数据,按照:('数据库名', 'String数据')

    1. Set('name', 'String'):往数据库中插入数据,一个字符型Redis数据库只能存放一个String
      name:表名;
      String:字符串,不限长
      Set()函数特别参数
      set(name, value, ex=None, px=None, nx=False, xx=False)
      ex,过期时间(秒)(若过期,Redis中name表也会被删除
      px,过期时间(毫秒)
      nx,如果设置为True,则只有name不存在时,当前set操作才执行
      xx,如果设置为True,则只有name存在时,当前set操作才执行
    r.set('Name', 'Lisi')   # 添加
    print(r.get('Name'))    # 获取'Name'表里数据
    
  2. 列表操作(存储数据用一个队列,一边进一边出):List

添加数据函数
lpush('表名', 数据):使每个新数据从列表左边插入
rpush('表名', 数据):使每个新数据从列表右边插入

import redis

r = redis.Redis(host='127.0.0.1', port=6379, db=1)  # 尽量别使用db0
# list操作
r.lpush('list_name', 3, 4, 5)

在这里插入图片描述
函数插入时是从列表左端开始插入Redis数据库中的,()为插入顺序
lpush:数据添加是 5(3)–>4(2)–>3(1)

rpush:数据添加是3(1)–>4(2)–>5(3)

删除表内数据
r.lpop("表名"):将Redis数据库表取出,从表的左端删除数据,也就是第一项开始
r.rpop("表名"):将Redis数据库表取出,从表的右端删除数据,也就是最后一项开始

检查表内数据长度
llen(‘表名’):显示表内数据多少;
例子:

r.llen("list_name")

2.简单的例子:

import redis
import time

r = redis.Redis(host='127.0.0.1', port=6379, db=1, decode_responses=True)  # 尽量别使用db0
# # list长度
print(r.llen("list_name"))
while True:
    if r.llen("list_name") < 10:
        r.rpush("list_name", 1, 2)  # 一次传出两个
    else:
        time.sleep(2)
        print('存储数据量已经大于10')

制造一个源源不断向Redis数据库中存储数据的程序:
若list_name表中数据长度llen(“list_name”) < 10个数据:
则源源不断往输入数据,一次传入两个——1,2
如果不是,数据大于10
就显示存储数据量已经大于10

3.Redis简单的项目

代理IP传入

import redis
import requests
from lxml import etree
import time

# 存Redis数据库
r = redis.Redis(host='127.0.0.1', port=6379, db=1, decode_responses=True)

print(r.llen("list_IP"))
while True:
    if r.llen("list_IP") < 5:
        source = requests.get(
            'http://webapi.http.zhimacangku.com/getip?num=2&type=2&pro=&city=0&yys=0&port=11&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=').json()
        # num=2 显示一次返回2个IP
        print(source)
        for i in source['data']:
            print(i)
            ip = i['ip']
            port = i['port']
            r.rpush("list_IP", str(ip) + ":" + str(port) + '|0')    # 增加计数|0
    else:
        print('正在补充IP,现有数量', r.llen("list_IP"))
        time.sleep(2)

获取付费代理IP

source = requests.get('http://webapi.http.zhimacangku.com/getip?num=2&type=2&pro=&city=0&yys=0&port=11&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=').json()   

链接中,num=2代表一次返回两个数据,若num=1则返回一个代理IP
返回实例:
返回的是一个字典dict
source[‘data’],找到source里的data
并把两个代理IP提取出来

      {
          "code":0,
          "success":true,
          "msg":"0",
          "data":[
              {
                  "ip":"49.68.68.197",
                  "port":33220,
                  "expire_time":"2019-05-24 08:58:31",
                  "city":"徐州市",
                  "isp":"电信"
              },
              {
                  "ip":"58.218.201.108", //隧道ip (代理ip)
                  "port":2690,           // 代理端口
                  "expire_time":"2019-05-24 08:55:31",
                  "city":"苏州市",
                  "isp":"电信",
                  "outip":"219.136.47.161",  // 隧道ip的出口ip
              }
          ]
        }

增加代理IP访问问题机制str(port) + '|0') 用 0 来进行计数
使用rpush()传入Redis数据库list_IP表里

r.rpush("list_IP", str(ip) + ":" + str(port) + '|0') 

验证代理IP

验证网页:https://2022.ip138.com/

网页需要经过headers验证

import requests
from lxml import etree
import redis
import time

# 需要加headers头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36'
}

r = redis.Redis(host='127.0.0.1', port=6379, db=1, decode_responses=True)
for i in range(5):
    rr = r.lpop('list_IP').split('|')	# 将list_IP通过"|"分开
    # 112.194.89.213:4245|0
    # rr = [112.194.89.213:4245, 0]
    ip = rr[0]
    num = int(rr[1])  # 计数
    proxies = {
        'https': 'http://' + ip
    }
    print(proxies)
    try:
        response = requests.get('https://2022.ip138.com/', headers=headers, proxies=proxies, timeout=5)  # 加headers头,proxy代理, timeout=5设置超时时间5s
    except:
        num = num + 1
        if num < 3:
            r.rpush("list_IP", ip + '|' + str(num))
            print('请求失败', ip + '|' + str(num))
        else:
            print('舍弃', ip)
        continue
    source = response.text		# 显示资源内容
    content = etree.HTML(source).xpath('/html/body/p[1]//text()')	#爬取整个网页html源码
    print(content)
    print(type(response.status_code))   # 看状态码字符类型
    if response.status_code == 200:	# 若访问成功
        r.rpush("list_IP", ip + '|' + '0')  # 若成功一次则将之前失败数据全部清除
    else:
        num = num + 1
        if num < 3:
            r.rpush("list_IP", ip + '|' + str(num))
        else:
            print('舍弃', ip)

在目标网页上使用代理IP

response = requests.get('https://2022.ip138.com/', headers=headers, proxies=proxies, timeout=5)  
# 加headers头,proxy代理, timeout=5设置超时时间5s

timeout=5——设置代理IP转载期限,超过5s则为劣质IP得舍弃
proxies=proxies——传入的代理IP

    proxies = {
        'https': 'http://' + ip	# 前必须为'https'
    }

取出IP,再将IP放回:
我们定义一个num来查看IP是否访问成功,若成功则num=0,若不成功,则num+1;当num超过3时,就代表该IP为劣质IP,则从Redis数据库中舍弃;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值