爬虫所用到的函数与基本思想:
1.初始化函数 url headers html result_ip(存放可用ip)2.start函数 for循环遍历前10的ip 调用请求函数和解析函数
3.请求函数 url ip 如果ip为空,不使用代理ip发起请求获取源代码,ip不为none,说明这次请求是用来测试代理ip是否可用
4.解析函数 根据正则匹配ip_port数据,for循环遍历每一个ip_port,使用get_html请求函数检测ip_port是否可用,如果可用判断result_ip是否已有,如果没有添加到列表中
5.检测列表中已有ip是否可用函数 for循环遍历已有ip,使用get_html检测是否可用,将不可用的取出,如果列表中可用ip小于5个,就重新启动爬虫函数
import re
from urllib import request,parse
# 引入设置请求头的类
from fake_useragent import UserAgent
#设置类的对象
agent = UserAgent()
import time
定义爬虫类与初始化函数
class IpSpider(object):
def __init__(self):
self.url = 'https://www.kuaidaili.com/free/inha/'
self.headers = {'User-Agent': agent.random}
self.html = ''