實例如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
import urllib.request import os, re,sys,time try: from StringIO import StringIO except ImportError: from io import StringIO loca = re.compile(r"""ion":"\D+", "ti""") #偽裝成瀏覽器 header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'} class Getip(): def __init__(self,diqu): self.ur ={"xicidaili國內(nèi)普通代理 --1線":"http://www.xicidaili.com/nt/", "ip84國內(nèi)普通代理 --2線":'http://www.ip84.com/dlpn-http/', 'xicidaili國內(nèi)高匿名代理 --1線':'http://www.xicidaili.com/nn/', 'ip84國內(nèi)高匿名代理 --2線':'http://www.ip84.com/dlgn-http/', 'xicidaili國外高匿名代理 --1線':'http://www.xicidaili.com/wn/', 'ip84國外高匿名代理 --2線':'http://www.ip84.com/gwgn-http/', 'xicidaili國外普通代理 --1線':'http://www.xicidaili.com/wt/', 'haodailiip國內(nèi)混合代理 --3線':'http://www.haodailiip.com/guonei/', 'haodailiip國外混合代理 --3線':'http://www.haodailiip.com/guoji/', } self.diqu = diqu def urlopen(self,url): global header try: req = urllib.request.Request(url, None, header) res=urllib.request.urlopen(req) return res except: pass def getip(self,ren): '''url = "http://proxy.ipcn.org/proxylist.html"#代理IP頁面 ip_proxy_re = re.compile(r"""\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,}""")# 直接匹配 xxx.xxx.xxx.xxx:xxxx''' url = self.ur[self.diqu]+str(ren) ip_proxy_re = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*</ td >\s*< td >\s*(\d{1,})\s*</ td >\s*<[^\u4E00-\u9FA5]+>([\u4E00-\u9FA5]*\s*[\u4E00-\u9FA5]*\s*[\u4E00-\u9FA5]*)\s*<') #################################通用正則匹配的 格式 是 (IP,端口,地區(qū)) 地區(qū)有可能包含換行和空格 try: data = self.urlopen(url).read().decode('utf-8') except: return None self.rel = [] ip = ip_proxy_re.findall(data) ##########返回的IP 就是 正則匹配的結(jié)果(IP,端口,地區(qū)) 地區(qū)有可能包含換行和空格 return ip if __name__ == '__main__': g=Getip("xicidaili國內(nèi)普通代理 --1線") import pprint for x in range(4): ips = g.getip(1) print('獲取到ip地址一共:',len(ips)) pprint.pprint(ips) |
以上這篇python 爬蟲 批量獲取代理ip的實例代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/mzbqhbc12/article/details/54996578