python代理ip的方法?這個(gè)問(wèn)題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見(jiàn)到的。希望通過(guò)這個(gè)問(wèn)題能讓你收獲頗深。下面是小編給大家?guī)?lái)的參考內(nèi)容,讓我們一起來(lái)看看吧!
創(chuàng)新互聯(lián)公司堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站制作、做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的硯山網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
使用到的庫(kù)
from bs4 import BeautifulSoup import random import urllib.request
下面是對(duì)該網(wǎng)站的簡(jiǎn)單解析提取HTTP的高匿IP
使用BeautifulSoup進(jìn)行網(wǎng)頁(yè)解析
def get_proxy_list(): target = 'http://www.xicidaili.com/nn/' + str(random.randint(0, 100)) try: opener = urllib.request.build_opener() #header可以選自己瀏覽器的 #樣例:[('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) ''AppleWebKit/537.36 (KHTML,like Gecko)Chrome/56.0.2924.87 Safari/537.36')] opener.addheaders = self.headers urllib.request.install_opener(opener) html = urllib.request.urlopen(target).read().decode('utf-8') tr = BeautifulSoup(html, 'lxml').find_all('tr') p = re.compile('<[^>]+>') for tag in tr: td_list = tag.find_all('td') if len(td_list) > 0: if str(td_list[5]) == '<td>HTTP</td>': #將爬到的代理IP存到列表里面 self.proxy_list.append(p.sub('', str(td_list[1])) + ':' + p.sub('', str(td_list[2]))) except Exception as b: self.logger.exception(b)
接下來(lái)就是代理IP的使用
使用的是urllib這個(gè)庫(kù),到了python3以后這個(gè)庫(kù)可以進(jìn)行的操作比之前更多,也可以進(jìn)行一些復(fù)雜連接的模擬了。
def init_urllib(): #這個(gè)函數(shù)用來(lái)初始化urllib的參數(shù) length = len(self.proxy_list) if length == 0: get_proxy_list() #隨機(jī)得到一個(gè)IP ip = random.choice(self.proxy_list) self.proxy_list.remove(ip) proxy = {'http': ip} proxy_support = urllib.request.ProxyHandler(proxy) #加載代理 opener = urllib.request.build_opener(proxy_support) opener.addheaders = self.headers #初始化urllib urllib.request.install_opener(opener) def connect(uri): html = '' flag = 20 while flag > 0: try: html = urllib.request.urlopen(uri).read().decode('utf-8') break except Exception as b: #這里可以將異常細(xì)化,由于是簡(jiǎn)單實(shí)現(xiàn)就不做具體實(shí)現(xiàn)了 self.logger.exception(b) #實(shí)現(xiàn)更換IP重新請(qǐng)求 flag -= 1 init_urllib() return BeautifulSoup( html, 'lxml')
感謝各位的閱讀!看完上述內(nèi)容,你們對(duì)python代理ip的方法大概了解了嗎?希望文章內(nèi)容對(duì)大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
當(dāng)前名稱:python代理ip的方法
本文URL:http://aaarwkj.com/article18/gjijgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計(jì)、網(wǎng)站營(yíng)銷、Google、品牌網(wǎng)站建設(shè)、網(wǎng)站維護(hù)、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)