用scrapy爬取可用的代理

一、分析免费代理网站的结构

  • 我爬取了三个字段:IPporttypeTIM图片20181118171534.jpg

二、分析要爬取的数据,编写items.py

  • 因此在items.py中,建立相应的字段
import scrapy
class IproxyItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    ip = scrapy.Field()
    type = scrapy.Field()
    port = scrapy.Field()

三、爬取所有的免费ip- 在spider目录下,创建IpSpider.py

import scrapy
import Iproxy.items
class IpSpider(scrapy.Spider):
    name = 'IpSpider'
    allowed_domains = ['xicidaili.com']
    start_urls = ['http://www.xicidaili.com/']

    def parse(self, response):
        item = Iproxy.items.IproxyItem()
        item['ip'] = response.css('tr td:nth-child(2)::text').extract()
        item['port'] = response.css('tr td:nth-child(3)::text').extract()
        item['type'] = response.css('tr td:nth-child(6) ::text').extract()
        yield item

四、检测是否可用,如果可用则存入数据库- 因为是免费的ip,所以我们有必要检测一下他是否可用,对于可用的就存入数据库,反之则丢弃- 检测处理数据在pipeline.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
import requests

class IproxyPipeline(object):
    def process_item(self, item, spider):
        print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
        db = pymysql.connect("localhost", "root", "168168", "spider")
        cursor = db.cursor()
        for i in range(1, len(item['ip'])):
            ip = item['ip'][i] + ':' + item['port'][i]
            try:
                if self.proxyIpCheck(ip) is False:
                    print('此ip:'+ip+"不能用")
                    continue
                else:
                    print('此ip:'+ip+'可用,存入数据库!')
                    sql = 'insert into proxyIp value ("%s")' % (ip)
                    cursor.execute(sql)
                    db.commit()
            except:
                db.rollback()
        db.close()
        return item

    def proxyIpCheck(self, ip):
        proxies = {'http': 'http://' + ip, 'https': 'https://' + ip}
        try:
            r = requests.get('https://www.baidu.com/', proxies=proxies, timeout=1)
            if (r.status_code == 200):
                return True
            else:
                return False
        except:
            return False


五、运行情况- 可以看出还是有好多ip不能用的TIM图片20181118172712.png- 可用的存在数据库

TIM图片20181118172841.jpg

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值