您的位置:首页 > 编程语言 > Python开发

Python爬虫获取代理ip及端口

2018-03-06 15:43 706 查看
'''
爬取代理ip
可以作为模块使用,在使用代理ip的时候直接调用该模块即可。
'''
import re
import urllib.request

def ExtractIP(url='http://www.xicidaili.com/'):
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0'}

# urllib.request.Request()用于向服务端发送请求,就如 http 协议客户端向服务端发送请求 POST
# 添加了一个头部,伪装成浏览器,此时的url并不是一个裸露的url,而是具有header头部的url
req = urllib.request.Request(url=url, headers=headers)

response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
# print(html)
#构造正则表达式
p = re.compile(r'<td>((([01]\d{0,2}|2[0-4]\d|25[0-5])\.){3}([01]\d{0,2}|2[0-4]\d|25[0-5]))</td>')

res = p.finditer(html)

#字典存储所有的ip及端口号
ip_port = dict()
for each_http in res:
# print(each_http.group(1))
location = each_http.end()
a = html.find('<td>', location) + 4
b = html.find('</td>', location)
port_num = html[a:b]
# print(port_num)
'''
端口号范围:0-65535
'''
if int(port_num) >=0 and int(port_num) <= 65535:
ip_port[each_http.group(1)] = port_num

return ip_port

if __name__ == '__main__':
'''
代理ip的URL百度获取即可
'''
url = 'http://www.xicidaili.com/'
result = ExtractIP(url)
print(result)
print(len(result))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: