python爬取代理ip

要写爬虫爬取大量的数据,就会面临ip被封的问题,虽然能够经过设置延时的方法来延缓对网站的访问,可是一旦访问次数过多仍然会面临ip被封的风险,这时咱们就须要用到动态的ip地址来隐藏真实的ip信息,若是作爬虫项目,建议选取一些平台提供的动态ip服务,引用api便可。目前国内有不少提供动态ip的平台,广泛价格不菲,而对于只想跑个小项目用来学习的话能够参考下本篇文章。html

简述

本篇使用简单的爬虫程序来爬取免费ip网站的ip信息并生成json文档,存储可用的ip地址,写其它爬取项目的时候能够从生成的json文档中提取ip地址使用,为了确保使用的ip地址的有效性,建议对json文档中的ip现爬现用,而且在爬取时对ip有效性的时间进行筛选,只爬取时长较长、可用的ip地址存储。json

实现

使用平台https://www.xicidaili.com/nn/来做为数据源,经过对http://www.baidu.com/的相应来判断ip的可以使用性。引用lxml模块来对网页数据进行提取,固然也能够使用re模块来进行匹配提取,这里只使用lxml模块对数据进行提取。
访问https://www.xicidaili.com/nn/数据源,而且启动Fiddler对浏览器数据进行监听,我这里浏览器采用的是Proxy SwitchyOmega插件来配合Fiddler进行使用,在Fiddler找到/nn/*数据查看User-Agent信息并复制下来做为咱们访问的头文件。如图:

引入模块api

import requests
from lxml import etree
import time
import json

获取全部数据浏览器

def get_all_proxy(page):
    url = 'https://www.xicidaili.com/nn/%s'%page
    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_ele = etree.HTML(response.text)
    ip_eles = html_ele.xpath('//table[@id="ip_list"]/tr/td[2]/text()')
    port_ele = html_ele.xpath('//table[@id="ip_list"]/tr/td[3]/text()')
    print(ip_eles)
    proxy_list = []
    for i in range(0,len(ip_eles)):
        check_all_proxy(ip_eles[i],port_ele[i])
    return proxy_list

对数据进行筛选:app

def check_all_proxy(host,port):
    type = 'http'
    proxies = {}
    proxy_str = "%s://@%s:%s" % (type, host, port)
    valid_proxy_list = []
    url = 'http://www.baidu.com/'
    proxy_dict = {
            'http': proxy_str,
            'https': proxy_str
        }
    try:
            start_time = time.time()
            response = requests.get(url, proxies=proxy_dict, timeout=5)
            if response.status_code == 200:
                end_time = time.time()
                print('代理可用:' + proxy_str)
                print('耗时:' + str(end_time - start_time))
                proxies['type'] = type
                proxies['host'] = host
                proxies['port'] = port
                proxiesJson = json.dumps(proxies)
                with open('verified_y.json', 'a+') as f:
                    f.write(proxiesJson + '\n')
                print("已写入:%s" % proxy_str)
                valid_proxy_list.append(proxy_str)
            else:
                print('代理超时')
    except:
            print('代理不可用--------------->'+proxy_str)

运行程序:学习

if __name__ == '__main__':
    for i in range(1,11): #选取前十页数据使用
       proxy_list = get_all_proxy(i)
       time.sleep(20)
       print(valid_proxy_list)

生成的json文件:
网站

相关文章
相关标签/搜索