爬虫--多线程爬取可以使用的西刺代理ip

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MR_HJY/article/details/81915724
import requests
from lxml import etree
import time
import multiprocessing


def get_all_proxy(queue):
    url = 'http://www.xicidaili.com/nn/1'

    headers ={
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
    }
    response = requests.get(url, headers=headers)

    html_element = etree.HTML(response.text)
    ip_element = html_element.xpath('//table[@id="ip_list"]/tr/td[2]/text()')
    port_element = html_element.xpath('//table[@id="ip_list"]/tr/td[3]/text()')

    proxy_list = []
    for i in range(0,len(ip_element)):
        proxy_str = 'http://' + ip_element[i] +':' + port_element[i]
        queue.put(proxy_str)

def check_one_proxy(proxy):
    try:
        url = 'http://www.baidu.com/s?wd=ip'
        proxy_dict = {
            'http': proxy
        }
        try:
            response = requests.get(url, proxies=proxy_dict, timeout=5)
            if response.status_code == 200:
                print('proxy:' + proxy)
                return proxy
            else:
                print('=== GG ===')
                return proxy
        except:
            return  None
    except Exception as e:
        print(e)


if __name__ == '__main__':
    start_time = time.time()

    # 创建队列
    q = multiprocessing.Queue()
    # 获取所有代理
    p = multiprocessing.Process(target=get_all_proxy, args=(q,))
    p.start()
    # 检测代理的可用性
    pool = multiprocessing.Pool(100)
    result_list = []
    while True:
        try:
            proxy_str = q.get(timeout=5)
        except:
            break
        proxy_res = pool.apply_async(check_one_proxy, (proxy_str,))
        result_list.append(proxy_res)

    vaild_proxy_list = []
    for proxy_res in result_list:
        result = proxy_res.get()
        if result is None:
            pass
        else:
            vaild_proxy_list.append(result)

    print('All proxy we can get:')
    print(vaild_proxy_list)
    pool.close()
    pool.join()
    p.join()

    end_time = time.time()
    print('---'*30)
    print('耗时:'+str(end_time-start_time))


猜你喜欢

转载自blog.csdn.net/MR_HJY/article/details/81915724