(python2)从西刺代理获取代理IP,构建代理IP池

 目前可以实现,从西刺获取ip地址,判断时候可用,将存活时间中带有(天)的IP(稳定性较好)提取出来放到txt文件中,供我们使用。

(注意:

现在每15分钟会进行更新,尽量每15分钟重新获取一次,还没有写这一部分代码信息)稍后更新!

#encoding=utf-8
# Created by double lin at 2018/8/20
import requests
from bs4 import BeautifulSoup

url = 'http://www.xicidaili.com/wn/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36',
    'Host': 'www.xicidaili.com'
}
url1 = 'http://www.xicidaili.com/api'
r = requests.get(url, headers=headers)
# print (r.text)

def get_html(url):
    r = requests.get(url, headers=headers)
    html = BeautifulSoup(r.text, 'html.parser')
    get_ip(html)

def get_ip(html):
    table = html.find('table')
    ip_text = table.findAll('tr')
    ip_List = []
    if ip_text is not None:
        print len(ip_text)

        # 得到每一条ip数据详细信息(在table中的一行,包含ip地址,以及其他的介绍信息
        for i in range(1, len(ip_text)):

            # 得到每一个ip信息中的每一个单独项信息,即每一个单元格的数据信息
            ipTag = ip_text[i].findAll('td')
            # for j in range(len(ipTag)):
            temp = {
                'ip_life': ipTag[8].get_text(),
                'ip_addr': ipTag[1].get_text()+':'+ipTag[2].get_text()
            }
            ip_List.append(temp)

    for i in range(len(ip_List)):
        print ip_List[i]['ip_life'], ip_List[i]['ip_addr']
        ip_confirm(ip_List[i]['ip_addr'])
        save_ip(ip_List)
    return ip_List

def ip_confirm(ip):
    try:
        requests.get('https://www.baidu.com/', proxies={"http": "https://%s" %ip})
    except:
        print 'failed'
    else:
        print 'true'


def save_ip(List):
    with open('proxy_ip-lin.txt', 'wb') as f:
        for i in range(len(List)):
            if i <= 50:
                if '天' in List[i]['ip_life']:
                    f.write(List[i]['ip_addr']+'\n')
    f.close()

if __name__ == '__main__':
    get_html(url)

谢谢大家,我们一起往前冲哈!!

猜你喜欢

转载自blog.csdn.net/qq_32670879/article/details/81948137
今日推荐