python爬取高匿代理IP(不再用擔憂會進小黑屋了)

爲何要用代理IP

不少數據網站,對於反爬蟲都作了必定的限制,這個若是寫過一些爬蟲程序的小夥伴應該都深有體會,其實主要仍是IP進了小黑屋了,那麼爲了安全,就不能使用本身的實際IP去爬取人家網站了,這個時候,就須要採用代理IP去作這些事情……html

爲何要用高匿代理

咱們能夠對比不一樣類型的代理的區別,根據代理的匿名程度,代理能夠分爲以下類別:python

  • 高度匿名代理:會將數據包原封不動的轉發,在服務端看來就好像真的是一個普通客戶端在訪問,而記錄的IP則是代理服務器的IP。git

  • 普通匿名代理:會在數據包上作一些改動,服務器上有可能發現這是個代理服務器,也有必定概率追查到客戶端的真實IP。github

  • 透明代理:不但改動了數據包,還會告訴服務器客戶端的真實IP。數據庫

  • 間諜代理:指組織或我的建立的用戶記錄用戶傳輸的數據,而後進行研究、監控等目的的代理服務器。json

運行環境

Python運行環境:Windows + python3.6
用到的模塊:requests、bs四、json
如未安裝的模塊,請使用pip instatll xxxxxx進行安裝,例如:pip install requests安全

爬取西刺代理IP

這裏,我只大概爬取西刺高匿代理50頁的數據,固然了,爬100頁,爬所有,都是能夠的,就很少說了;服務器

def run(self):
    """執行入口"""
    page_list = range(1, 51)
    with open("ip.json", "w") as write_file:
        for page in page_list:
            # 分頁爬取數據
            print('開始爬取第' + str(page) + '頁IP數據')
            ip_url = self.base_url + str(page)
            html = self.get_url_html(ip_url)
            soup = BeautifulSoup(html, 'html.parser')
            # IP列表
            ip_list = soup.select('#ip_list .odd')
            for ip_tr in ip_list:
                # 單條Ip信息
                td_list = ip_tr.select('td')
                ip_address = td_list[1].get_text()
                ip_port = td_list[2].get_text()
                ip_type = td_list[5].get_text()
                info = {'ip': ip_address, 'port': ip_port, 'type': ip_type}
                # 先校驗一下IP的有效性再存儲
                check_res = self.check_ip(info)
                if check_res:
                    print('IP有效:', info)
                    self.json_data.append(info)
                else:
                    print('IP無效:', info)
        json.dump(self.json_data, write_file)
複製代碼

檢測代理IP是否有效

爬取到的代理IP可能不能用,爲了方便使用的時候,不報太多異常錯誤,因此須要先檢測一下IP是否能正常使用,是不是有效代理IP,我這裏列了三個網站,均可以很方便的檢測IP地址是否能有效使用app

def check_ip(self, ip_info):
    """測試IP地址是否有效"""
    ip_url = ip_info['ip'] + ':' + str(ip_info['port'])
    proxies = {'http': 'http://' + ip_url, 'https': 'https://' + ip_url}
    res = False
    try:
        request = requests.get(url=self.check_url, headers=self.header, proxies=proxies, timeout=3)
        if request.status_code == 200:
            res = True
    except Exception as error_info:
        res = False
    return res
複製代碼

存儲代理IP

我這裏就不搞那些花裏胡哨的,我直接把全部有效的代理IP的json格式的數據存儲到文件中,固然了,也能夠存儲到MongoDB或者MySQL數據庫中,無論怎樣存儲,在使用的時候都是隨機選取一個IP,更加方便快捷。工具

完整代碼

代碼我已經上傳了GitHub(GitHub源碼地址),可是呢,做爲一個熱心的搬瓦工,爲了方便部分人想偷懶,不直接去交友網站查看,我在這裏也貼一下源碼出來吧,若是有啥問題,最好仍是去交友網站找我,請接碼……

#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" 利用requests+bs4爬取國內高匿代理IP author: gxcuizy date: 2020-06-19 """

import requests
from bs4 import BeautifulSoup
import json


class GetIpData(object):
    """爬取50頁國內高匿代理IP"""
    header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'}
    base_url = 'https://www.xicidaili.com/nn/'
    check_url = 'https://www.ip.cn/'
    json_data = []

    def get_url_html(self, url):
        """請求頁面html"""
        request = requests.get(url=url, headers=self.header, timeout=5)
        html = False
        if request.status_code == 200:
            html = request.content
        return html

    def check_ip(self, ip_info):
        """測試IP地址是否有效"""
        ip_url = ip_info['ip'] + ':' + str(ip_info['port'])
        proxies = {'http': 'http://' + ip_url, 'https': 'https://' + ip_url}
        res = False
        try:
            request = requests.get(url=self.check_url, headers=self.header, proxies=proxies, timeout=3)
            if request.status_code == 200:
                res = True
        except Exception as error_info:
            res = False
        return res

    def run(self):
        """執行入口"""
        page_list = range(1, 51)
        with open("ip.json", "w") as write_file:
            for page in page_list:
                # 分頁爬取數據
                print('開始爬取第' + str(page) + '頁IP數據')
                ip_url = self.base_url + str(page)
                html = self.get_url_html(ip_url)
                soup = BeautifulSoup(html, 'html.parser')
                # IP列表
                ip_list = soup.select('#ip_list .odd')
                for ip_tr in ip_list:
                    # 單條Ip信息
                    td_list = ip_tr.select('td')
                    ip_address = td_list[1].get_text()
                    ip_port = td_list[2].get_text()
                    ip_type = td_list[5].get_text()
                    info = {'ip': ip_address, 'port': ip_port, 'type': ip_type}
                    # 先校驗一下IP的有效性再存儲
                    check_res = self.check_ip(info)
                    if check_res:
                        print('IP有效:', info)
                        self.json_data.append(info)
                    else:
                        print('IP無效:', info)
            json.dump(self.json_data, write_file)


# 程序主入口
if __name__ == '__main__':
    # 實例化
    ip = GetIpData()
    # 執行腳本
    ip.run()
複製代碼

最後

老規矩,你們有任何問題,均可以留言或者各類渠道告訴我,你們能夠相互學習和交流,共同成長……

相關文章
相關標籤/搜索