使用scrapy爬取代理ip

现在的网站基本上都会有防爬虫机制,其中最常用的就是根据ip来ban爬虫,因此当需要有大量的请求时,就需要用到代理请求了。

本次爬取的是的网页是www.xicidaili.com

这个网站中将代理ip进行了分类,比如http的或者是https的

例如http代理的url为http://www.xicidaili.com/wt/


定义的容器

class GetproxyItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    ip = scrapy.Field()
    port = scrapy.Field()
    protocol = scrapy.Field()
    delay = scrapy.Field()
    pass

爬虫

import re
import scrapy
from bs4.testing import BeautifulSoup
from scrapy.http import Request
from getProxy.items import GetproxyItem
from getProxy.settings import MAX_DELAY

class Myspider(scrapy.Spider):
    name = 'proxyip'
    bashurl = [
        #'http://www.xicidaili.com/wn/',#https
        'http://www.xicidaili.com/wt/'#http
    ]

    def start_requests(self):
        length = len(self.bashurl)
        for i in range(0, length):
            url = self.bashurl[i]
            yield Request(url, self.parse)

    def parse(self, response):
        max_num = BeautifulSoup(response.text,'lxml').find('div',class_= 'pagination').find_all('a')[-2].get_text()
        bashurl = str(response.url)
        for num in range(1, int(max_num) +1):
            url = bashurl + str(num)
            yield Request(url,callback = self.get_proxy)

    def get_proxy(self, response):
        item = GetproxyItem()
        proxys = BeautifulSoup(response.text, 'lxml').find('table',id = 'ip_list')
        length = len(proxys.find_all('tr'))
        for i in range(1,length):
            element = proxys.find_all('tr')[i]
            item['ip'] = element.find_all('td')[1].get_text()
            #item['ip'] += ':' + element.find_all('td')[2].get_text()
            item['port'] = element.find_all('td')[2].get_text()
            item['protocol'] = element.find_all('td')[5].get_text()
            item['delay'] = element.find_all('td')[6].find('div').attrs['title'][:-1]
            if float(item['delay']) > MAX_DELAY:
                continue
            yield item

配置文件setting

#筛选掉延迟高于2秒的ip
MAX_DELAY = 2.0
执行爬虫的时候使用命令

scrapy crawl proxyip -o ../proxy_http.json'
即可将爬取的IP保存到项目根目录的proxy_http.json文件中

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值