利用Python爬取免費代理IP


#       2019/9/8
#       思路:   1、找到一個免費的ip代理網站(如:西刺代理)
#
#                  2、爬取ip(常規爬取requests+BeautifulSoup)
#
#                  3、驗證ip有效性(攜帶爬取到的ip,去訪問指定的url,看返回的狀態碼是不是200)
#
#                  4、記錄ip (寫到文檔)


# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests, threading, datetime
from bs4 import BeautifulSoup
import random

"""
1、抓取西刺代理網站的代理ip
2、並根據指定的目標url,對抓取到ip的有效性進行驗證
3、最后存到指定的path
"""


# ------------------------------------------------------文檔處理--------------------------------------------------------
# 寫入文檔
def write(path, text):
    with open(path, 'a', encoding='utf-8') as f:
        f.writelines(text)
        f.write('\n')
        f.close()


# 清空文檔
def truncatefile(path):
    with open(path, 'w', encoding='utf-8') as f:
        f.truncate()


# 讀取文檔
def read(path):
    with open(path, 'r', encoding='utf-8') as f:
        txt = []
        for s in f.readlines():
            txt.append(s.strip())
    return txt


# ----------------------------------------------------------------------------------------------------------------------
# 計算時間差,格式: 時分秒
def gettimediff(start, end):
    seconds = (end - start).seconds
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    diff = ("%02d:%02d:%02d" % (h, m, s))
    return diff


# ----------------------------------------------------------------------------------------------------------------------
# 返回一個隨機的請求頭 headers
def getheaders():
    user_agent_list = [ \
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1" \
        "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", \
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6", \
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6", \
        "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1", \
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5", \
        "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5", \
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", \
        "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", \
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", \
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", \
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", \
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", \
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", \
        "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", \
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3", \
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", \
        "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
    ]
    UserAgent = random.choice(user_agent_list)
    headers = {'User-Agent': UserAgent}
    return headers


# -----------------------------------------------------檢查ip是否可用----------------------------------------------------
def checkip(targeturl, ip):
    headers = getheaders()  # 定制請求頭
    proxies = {"http": "http://" + ip, "https": "http://" + ip}  # 代理ip
    try:
        response = requests.get(url=targeturl, proxies=proxies, headers=headers, timeout=5).status_code
        if response == 200:
            return True
        else:
            return False
    except:
        return False


# -------------------------------------------------------獲取代理方法----------------------------------------------------
# 免費代理 XiciDaili
def findip(type, pagenum, targeturl, path):  # ip類型,頁碼,目標url,存放ip的路徑
    list = {'1': 'http://www.xicidaili.com/wn/',  # xicidaili國內https代理
    '2': 'http://www.xicidaili.com/nn/',  # xicidaili國內高匿代理
    '3': 'http://www.xicidaili.com/nt/',  # xicidaili國內普通代理
    '4': 'http://www.xicidaili.com/wt/'}  # xicidaili國外http代理
    url = list[str(type)] + str(pagenum)  # 配置url
    # print("url:",url)
    headers = getheaders()  # 定制請求頭
    html = requests.get(url=url, headers=headers, timeout=5).text
    # print("html:", html)
    soup = BeautifulSoup(html, 'lxml')
    all = soup.find_all('tr', class_='odd')
    for i in all:
        t = i.find_all('td')
        ip = t[1].text + ':' + t[2].text
        is_avail = checkip(targeturl, ip)
        if is_avail == True:
            write(path=path, text=ip)
            print(ip)


# -----------------------------------------------------多線程抓取ip入口---------------------------------------------------
def getip(targeturl, path):
    truncatefile(path)  # 爬取前清空文檔
    start = datetime.datetime.now()  # 開始時間
    threads = []
    for type in range(1):  # 四種類型ip,每種類型取前三頁,共12條線程
        for pagenum in range(3):
            t = threading.Thread(target=findip, args=(type + 1, pagenum + 1, targeturl, path))
            threads.append(t)
    print('開始爬取代理ip')
    for s in threads:  # 開啟多線程爬取
        s.start()
    for e in threads:  # 等待所有線程結束
        e.join()
    print('爬取完成')
    end = datetime.datetime.now()  # 結束時間
    diff = gettimediff(start, end)  # 計算耗時
    ips = read(path)  # 讀取爬到的ip數量
    print('一共爬取代理ip: %s 個,共耗時: %s \n' % (len(ips), diff))


# -------------------------------------------------------啟動-----------------------------------------------------------
if __name__ == '__main__':
    path = 'ip.txt'  # 存放爬取ip的文檔path
    targeturl = 'http://www.cnblogs.com/TurboWay/'  # 驗證ip有效性的指定url
    getip(targeturl, path)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM