• Python爬取代理IP


            在一些网页的内容爬取过程中,有时候在单位时间内如果我们发送的请求次数过多,网站就可能会封掉我们的IP地址,这时候为了保证我们的爬虫的正常运行,我们就要使用代理IP。

            下面来介绍如何构建自己的IP池。

    我们用快代理来获取代理ip地址:国内高匿免费HTTP代理IP - 快代理

            通过lxml模块的etree,我们很快就可以通过网页源码来获取储存代理ip地址和端口以及IP类型的标签,对它们的爬取也不是一件难事。

            IP爬到后接下来我们要验证我们爬取的IP是否是真正有效的,毕竟作为免费的IP,有效性还是不高的,需要我们进一步的甄别。

    在这里我再分享一个网站:

    http://icanhazip.com/

            通过访问这个网站,我们可以得到自己当前的IP地址,由此我们可以根据访问该网站得到的返回数据与我们使用的代理IP进行对比观察是否相同,就可以判断我们爬取的代理IP是否有效了。

            下面是完整代码:

    1. import requests
    2. from lxml import etree
    3. import time
    4. headers = {"User-Agent": "mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"}
    5. def get_ips():
    6. ls = []
    7. ipps = []
    8. for i in range(1, 3):
    9. url = f"https://free.kuaidaili.com/free/inha/{i}/"
    10. page = requests.get(url=url, headers=headers).text
    11. tree = etree.HTML(page)
    12. ips = tree.xpath('//table[@class="table table-bordered table-striped"]/tbody/tr')
    13. for i in ips:
    14. try:
    15. ip = "http://" + i.xpath('./td[@data-title="IP"]/text()')[0] + ":" + \
    16. i.xpath('./td[@data-title="PORT"]/text()')[0]
    17. ipps.append(ip)
    18. except:
    19. continue
    20. time.sleep(1)
    21. ipps = list(set(ipps))
    22. for ip in ipps:
    23. dic = {}
    24. dic["http"] = ip
    25. ls.append(dic)
    26. return ls
    27. def check_ips(ls):
    28. url = 'http://icanhazip.com/'
    29. for i in ls[::-1]:
    30. try:
    31. r = requests.get(url=url, headers=headers, proxies=i,timeout=5)
    32. r.raise_for_status()
    33. if r.text[:13]==i['http'][7:20]:
    34. continue
    35. else:
    36. ls.remove(i)
    37. except:
    38. ls.remove(i)
    39. return ls
    40. def ips():
    41. a=get_ips()
    42. b=check_ips(a)
    43. return b
    44. if __name__ == '__main__':
    45. print(ips())

            上述代码我仅爬取快代理网站的前两页IP内容,如需更多,可更改get_ips()函数第一个for循环的次数。但是这种方法也有一个弊端,我是一页一页的爬取,然后把爬取的代理IP一个一个的判断,速度会慢下来不少。为了更高效的爬取,我们可以导入线程池,在爬取和验证的过程中均导入线程池,可以让我们爬取的速度成倍增长。

    1. import requests
    2. from lxml import etree
    3. from multiprocessing.dummy import Pool
    4. headers = {"User-Agent": "mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"}
    5. ls=[]
    6. ipps=[]
    7. def get_ips(a):
    8. url = f"https://free.kuaidaili.com/free/inha/{a}/"
    9. page = requests.get(url=url, headers=headers).text
    10. tree = etree.HTML(page)
    11. ips = tree.xpath('//table[@class="table table-bordered table-striped"]/tbody/tr')
    12. for i in ips:
    13. try:
    14. ip = "http://" + i.xpath('./td[@data-title="IP"]/text()')[0] + ":" + \
    15. i.xpath('./td[@data-title="PORT"]/text()')[0]
    16. ipps.append(ip)
    17. except:
    18. continue
    19. pool_1=Pool(2)
    20. pool_1.map(get_ips,list(range(1,3)))
    21. pool_1.close()
    22. pool_1.join()
    23. for ip in list(set(ipps)):
    24. dic={}
    25. dic['http']=ip
    26. ls.append(dic)
    27. print(len(ls))
    28. def check_ips(i):
    29. url = 'http://icanhazip.com/'
    30. try:
    31. r = requests.get(url=url, headers=headers, proxies=i,timeout=5)
    32. r.raise_for_status()
    33. if r.text[:13]==i['http'][7:20]:
    34. pass
    35. else:
    36. ls.remove(i)
    37. except:
    38. ls.remove(i)
    39. pool_2=Pool(15)
    40. pool_2.map(check_ips,ls)
    41. pool_2.close()
    42. pool_2.join()
    43. if __name__ == '__main__':
    44. print(ls)

    爬取前两页的代理IP,可以发现,基本上每5个代理IP中仅有1个是有用的,但毕竟这是免费的,我们仅仅是增加了一步验证的过程,总的来说,还是非常不错的。

     

  • 相关阅读:
    spring gateway给请求添加params
    JAVA基础(十)
    VUE+element可以为空不为空时只能为(正整数和0)的验证
    JSP介绍及常用方法
    《熟悉Set集合》 第二弹
    JAVA面试题大全希望能够挑动大家的味蕾!(附赠BAT面试大全)
    结构型设计模式之桥接模式
    SLAM从入门到精通(代码调试)
    Spring Cloud Alibaba-01-微服务介绍
    算法进阶——字符串的排列
  • 原文地址:https://blog.csdn.net/qq_60926106/article/details/125579727