前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Scrapy-从数据库取出IP并判断是否

Scrapy-从数据库取出IP并判断是否

作者头像
py3study
发布2020-01-17 11:43:49
7860
发布2020-01-17 11:43:49
举报
文章被收录于专栏:python3
代码语言:javascript
复制
import pymysql
import requests

conn = pymysql.connect(host="localhost",user="root",passwd="root",db="CDL",charset="utf8")
cursor = conn.cursor()
class IpUtils(object):

    # 删除无效ip
    def delete_ip(self,ip):
        sql ="delete from xiciproxy where ip='{0}'".format(ip)
        cursor.execute(sql)
        conn.commit()
        return True

    # 判断ip是否可用
    def judge_ip(self,type,ip,port):
        http_url ="http://www.baidu.com"
        proxy_url ="{0}://{1}:{2}".format(type,ip,port)
        print("url:"+ proxy_url)
        try:
            proxy_dict = {
                type: proxy_url, # type 为https 或者http 数据库存储的
            }
            response = requests.get(http_url,proxies=proxy_dict)
        exceptExceptionase:
            self.delete_ip(ip)
            print("invalid ip and port")
            return False
            code = response.status_code
            if code >=200 and code <300:
                print("effective ip")
                return True
        else:
            print("invalid ip and port")
            self.delete_ip(ip)
            return False
    # 随机获取IP
    def get_random_ip(self):
        random_sql ="""
            SELECT type, ip, port FROM xiciproxy
            ORDER BY RAND()
            LIMIT 1
        """
        result = cursor.execute(random_sql)
        for ip_info in cursor.fetchall():
            type = ip_info[0]
            ip = ip_info[1]
            port = ip_info[2]
            judge_re =self.judge_ip(type,ip,port)
            ifjudge_re:
            return"{0}://{1}:{2}".format(type,ip,port)
        else:
            return self.get_random_ip()
if__name__ =="__main__":
    Ip = IpUtils()
    print(Ip.get_random_ip())

2020考研打卡第二十天,星辰之变,骄阳岂是终点。 人生不如意十之八九,我怎么能放弃呢,老子一定要做大做强!!!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/05/30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档