本文實(shí)例講述了python實(shí)現(xiàn)ip代理池功能。分享給大家供大家參考,具體如下:
爬取的代理源為西刺代理。
- 用xpath解析頁(yè)面
- 用telnet來驗(yàn)證ip是否可用
- 把有效的ip寫入到本地txt中。當(dāng)然也可以寫入到redis、mongodb中,也可以設(shè)置檢測(cè)程序當(dāng)代理池中的ip數(shù)不夠(如:小于20個(gè))時(shí),啟動(dòng)該腳本來重新獲取ip,本腳本的代碼也要做相應(yīng)的改變。
# !/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): # 獲取頁(yè)面 req = urllib.request.Request('http://www.xicidaili.com/nn/{}'.format(page_num), headers=headers) # 構(gòu)造request請(qǐng)求 response = urllib.request.urlopen(req) # 發(fā)送請(qǐng)求 html = response.read() html = html.decode('utf-8') # print(html) # 解析頁(yè)面 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 # 檢測(cè)代理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頁(yè) proxy_ip_port_list += get_proxy(i) for i in range(100): # 一頁(yè)有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()
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
