温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python爬虫之如何抓取高匿ip代理

发布时间:2020-11-30 14:15:57 来源:亿速云 阅读:290 作者:小新 栏目:编程语言

小编给大家分享一下python爬虫之如何抓取高匿ip代理,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

很多网站都有反爬虫机制,只用一个ip去频繁访问网站的话,很容易引起网站管理员的注意,如果管理员将这个ip加入黑名单,那么这个爬虫就废掉了。所以,想要做大型的爬虫的话,基本上是必须要面对ip的问题。

那么问题来了,我们去哪里搞代理ip呢??第一种方法就是买买买!!没有什么事情是用钱解决不了的,如果有,那就加倍。

当然,网上也有一堆免费的ip代理,但是,免费的质量参差不齐,所以就需要进行筛选。以西刺代理为例:用爬虫爬取国内的高匿代理IP,并进行验证。(只爬取前五页,后面的失效太多,没有必要去验证了。)

class XiciSpider(scrapy.Spider):
    name = 'xici'
    allowed_domains = ['xicidaili.com']
    start_urls = []
    for i in range(1, 6):
        start_urls.append('http://www.xicidaili.com/nn/' + str(i))
 
    def parse(self, response):
        ip = response.xpath('//tr[@class]/td[2]/text()').extract()
        port = response.xpath('//tr[@class]/td[3]/text()').extract()
        agreement_type = response.xpath('//tr[@class]/td[6]/text()').extract()
        proxies = zip(ip, port, agreement_type)
        # print(proxies)
 
        # 验证代理是否可用
        for ip, port, agreement_type in proxies:
            proxy = {'http': agreement_type.lower() + '://' + ip + ':' + port,
                     'https': agreement_type.lower() + '://' + ip + ':' + port}
            try:
                # 设置代理链接  如果状态码为200 则表示该代理可以使用
                print(proxy)
                resp = requests.get('http://icanhazip.com', proxies=proxy, timeout=2)
                print(resp.status_code)
                if resp.status_code == 200:
                    print(resp.text)
                    # print('success %s' % ip)
                    item = DailiItem()
                    item['proxy'] = proxy
                    yield item
            except:
                print('fail %s' % ip)

Pipeline:

class DailiPipeline(object):
 
    def __init__(self):
        self.file = open('proxy.txt', 'w')
 
    def process_item(self, item, spider):
        self.file.write(str(item['proxy']) + '\n')
        return item
 
    def close_spider(self, spider):
        self.file.close()

以上是“python爬虫之如何抓取高匿ip代理”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI