上一篇说到对付反爬虫有一个很关键的方法就是使用IP代理,那么我们应该如何获取这些可用的IP代理呢?这里分享一下自己这两天的一些爬取IP代理的心得体会。
1 步骤
1.找到几个提供免费IP代理的网站,获取IP数据源
2.验证对应的IP代理访问出口IP是否跟本机的出口IP一致,得到不一致的IP代理列表
3.根据自身的实验目的验证IP代理的响应速度,进行排序,择优选用
2 具体做法
1.可以上网搜索,有很多,例如西刺、快代理等等
2.可以在这里进行验证
3.这个就根据自身爬虫的需要,看是下载东西还是其他的,再进一步测试速度
3 代码

1 # *-* coding: utf-8 *-*
2 import BeautifulSoup
3 import requests
4 import time
5
6 # to check if the ip proxy can work
7 URL_CHECK = 'http://1212.ip138.com/ic.asp'
8 RESPONSE_TIME = 2
9 IP_LOCAL = '120.236.174.144'
10
11 # this is the pages of the website "http://www.ip181.com/daili/1.html"
12 # you can check out in the browser.
13 # the program will crawl the ip proxy from pages [start_page, end_page]
14 # as: [1,2], it will crawl the page 1 and page 2.
15 start_page = input('Please input your start page to crawl: ')
16 end_page = input('Please input your end page to crawl: ')
17
18
19 s = requests.Session()
20
21 # check if the exit IP is changed
22 def check_a_ip(ip):
23 start = time.time()
24 try:
25 connection = s.get(URL_CHECK, headers={
26 'Host': '1212.ip138.com',
27 'Referer': 'http://www.ip138.com/',
28 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
29 }, proxies={'http': 'http://' + ip}, timeout=RESPONSE_TIME)
30 res = connection.content
31 # print res
32
33 soup = BeautifulSoup.BeautifulSoup(res)
34 ip_return = soup.findAll('center')[0].text.split('[')[1].split(']')[0]
35 return ip_return != IP_LOCAL, '%.6f' % (time.time() - start)
36 except Exception, e:
37 # print '<ERROR>'
38 # print e
39 return False, '-1'
40
41 url = 'http://www.ip181.com/daili/%s.html'
42 ip_proxy_file = open('proxy.txt', 'w')
43 ip_proxy_file.write('ip_port,response_time\n')
44 ip_proxy_file.close()
45
46 for i in range(int(start_page), int(end_page) + 1):
47 ip_proxy_file = open('proxy.txt', 'a')
48
49 connection_crawl = s.get(url % str(i),headers = {
50 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
51 })
52 soup_crawl = BeautifulSoup.BeautifulSoup(connection_crawl.content)
53
54 # parse each page,find the good ip proxy
55 trs = soup_crawl.findAll('tr')
56 for tr in trs[1:len(trs)]:
57 tds = tr.findAll('td')
58 ip = tds[0].contents[0] + ':' + tds[1].contents[0]
59 is_good, res_time = check_a_ip(ip)
60 if is_good:
61 ip_proxy_file.write(ip + ',' + res_time + '\n')
62
63 print '%s : Finish to crawl the page %d. %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), i, url % str(i))
64 ip_proxy_file.close()
关于这份代码,有几个地方做一下说明:
· check_a_ip(ip):该函数为IP代理检查函数,返回两个值(一个为访问请求是否成功使用了代理,一个为检查的响应时间)
· start_page、end_page: 手动输入获取IP代理的网页页码,这个需要根据具体网站设定
· for i in range(int(start_page), int(end_page) + 1):主函数的循环,遍历设定范围的网页
· for tr in trs[1:len(trs)]:循环遍历并解析出一个网页中的所有IP代理,以及检验是否可用
· ip_proxy_file:文本写入,最终把结果都写入proxy.txt中
4 拓展
本实验可以采用多线程进行爬取或者检验,这样的爬取速率会快很多,大家有时间可以尝试一下
来源:https://www.cnblogs.com/fangxx/p/python_crawl_proxy.html
