利用Python爬取可用的代理IP,python爬代理ip

來源:互聯網
上載者:User

利用Python爬取可用的代理IP,python爬代理ip

前言

就以最近發現的一個免費代理IP網站為例:http://www.xicidaili.com/nn/。在使用的時候發現很多IP都用不了。

所以用Python寫了個指令碼,該指令碼可以把能用的代理IP檢測出來。

指令碼如下:

#encoding=utf8import urllib2from bs4 import BeautifulSoupimport urllibimport socket User_Agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0'header = {}header['User-Agent'] = User_Agent '''擷取所有代理IP地址'''def getProxyIp(): proxy = [] for i in range(1,2):  try:   url = 'http://www.xicidaili.com/nn/'+str(i)   req = urllib2.Request(url,headers=header)   res = urllib2.urlopen(req).read()   soup = BeautifulSoup(res)   ips = soup.findAll('tr')   for x in range(1,len(ips)):    ip = ips[x]    tds = ip.findAll("td")    ip_temp = tds[1].contents[0]+"\t"+tds[2].contents[0]    proxy.append(ip_temp)  except:   continue return proxy  '''驗證獲得的代理IP地址是否可用'''def validateIp(proxy): url = "http://ip.chinaz.com/getip.aspx" f = open("E:\ip.txt","w") socket.setdefaulttimeout(3) for i in range(0,len(proxy)):  try:   ip = proxy[i].strip().split("\t")   proxy_host = "http://"+ip[0]+":"+ip[1]   proxy_temp = {"http":proxy_host}   res = urllib.urlopen(url,proxies=proxy_temp).read()   f.write(proxy[i]+'\n')   print proxy[i]  except Exception,e:   continue f.close()     if __name__ == '__main__': proxy = getProxyIp() validateIp(proxy)

 運行成功後,開啟E盤下的檔案,可以看到如下可用的代理IP地址和連接埠:

總結

這隻是爬取的第一頁的IP地址,如有需要,可以多爬取幾頁。同時,該網站是時時更新的,建議爬取時只爬取前幾頁的即可。以上就是本文的全部內容,希望對大家學習使用Python能有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.