zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python获取免费的可用代理

Python代理 获取 免费 可用
2023-09-14 09:06:19 时间

Python获取免费的可用代理

在使用爬虫多次爬取同一站点时,常常会被站点的ip反爬虫机制给禁掉,这时就能够通过使用代理来解决。眼下网上有非常多提供最新免费代理列表的站点。这些列表里非常多的代理主机是可用的,可是也有一些是不可用的,因此须要进一步筛选。利用Python能够非常方便地筛选出可用的代理列表。

以提供免费代理信息的站点IPCN 国家地区免费代理为例,这里给出一个爬取此站点上提供的代理信息并筛选可用代理主机的程序。主要用到requests和lxml,详细代码为:

# -*- coding: utf-8 -*-

import requests
from lxml import etree


def get_proxies_from_site():
    url = 'http://proxy.ipcn.org/country/'
    xpath = '/html/body/div[last()]/table[last()]/tr/td/text()'

    r = requests.get(url)
    tree = etree.HTML(r.text)

    results = tree.xpath(xpath)
    proxies = [line.strip() for line in results]

    return proxies

#使用http://lwons.com/wx网页来測试代理主机是否可用
def get_valid_proxies(proxies, count):
    url = 'http://lwons.com/wx'
    results = []
    cur = 0
    for p in proxies:
        proxy = {'http': 'http://' + p}
        succeed = False
        try:
            r = requests.get(url, proxies=proxy)
            if r.text == 'default':
                succeed = True
        except Exception, e:
            print 'error:', p
            succeed = False
        if succeed:
            print 'succeed:', p
            results.append(p)
            cur += 1
            if cur >= count:
                break

if __name__ == '__main__':
    print 'get ' + str(len(get_valid_proxies(get_proxies_from_site(), 20))) + ' proxies'