本文實(shí)例講述了python實(shí)現(xiàn)ip代理池功能。分享給大家供大家參考,具體如下:
爬取的代理源為西刺代理。
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Version : 1.0 # @Time : 2018/10/23 上午10:40 # @Author : Yeoman # @Description : import urllib.request import lxml.etree import telnetlib import os headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36' } def get_proxy(page_num): # 獲取頁面 req = urllib.request.Request('http://www.xicidaili.com/nn/{}'.format(page_num), headers=headers) # 構(gòu)造request請求 response = urllib.request.urlopen(req) # 發(fā)送請求 html = response.read() html = html.decode('utf-8') # print(html) # 解析頁面 proxy_list = [] selector = lxml.etree.HTML(html) rows = selector.xpath('//*[@id="ip_list"]//tr') rows_total = len(rows) row_xpath_head = '//*[@id="ip_list"]//tr[' row_ip_xpath_tail = ']/td[2]/text()' row_port_xpath_tail = ']/td[3]/text()' for i in range(1, rows_total): ip_xpath = row_xpath_head + str(i+1) + row_ip_xpath_tail port_xpath = row_xpath_head + str(i+1) + row_port_xpath_tail ip = selector.xpath(ip_xpath)[0] port = selector.xpath(port_xpath)[0] ip_port = ip + ':' + port proxy_list.append(ip_port) return proxy_list # 檢測代理ip是否可用 def test_proxy_ip_port(proxy_ip_port): print('當(dāng)前代理ip:{}'.format(proxy_ip_port)) ip_port = proxy_ip_port.split(':') ip = ip_port[0] port = ip_port[1] # 用telnet來驗(yàn)證ip是否可用 try: telnetlib.Telnet(ip, port, timeout=10) except: return False else: return True # 把有效的ip寫入本地 def write_ip(proxy_ip): with open('./ip.txt', 'a') as f: f.write(proxy_ip + '\n') # 刪除文件 def del_file(): file_path = './ip.txt' if os.path.exists(file_path): os.remove(file_path) def run(): del_file() proxy_ip_port_list = [] for i in range(1, 6): # 前5頁 proxy_ip_port_list += get_proxy(i) for i in range(100): # 一頁有100條 proxy_ip_port = proxy_ip_port_list[i] is_valid = test_proxy_ip_port(proxy_ip_port) print(is_valid) if is_valid: # 寫入ip到本地 write_ip(proxy_ip_port) if __name__ == '__main__': run()
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
新聞標(biāo)題:python實(shí)現(xiàn)ip代理池功能示例-創(chuàng)新互聯(lián)
鏈接URL:http://chinadenli.net/article16/epsgg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、定制開發(fā)、網(wǎng)頁設(shè)計(jì)公司、云服務(wù)器、小程序開發(fā)、定制網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容