1.前言
在爬取网站的过程中,很多网站都有反爬机制,它可能会限制每个Ip的访问速度或访问次数。如果限制访问的速度,则可以通过time.sleep进行短暂休眠后再次爬取。但是对于限制Ip访问次数的时候,则必须通过代理Ip轮换去访问目标网址。所以需要构建子的IP池。
2.第一步:找到一些IP代理的网站,如快代理。
通过一般的爬虫思路将IP爬取下来,将爬下来的IP放在列表中存起来,要注意的是IP的格式一般为字典{HTTP:Ip:端口}。
代码如下:
import requests
import parsel
import time
ip_list = []
for i in range(1,30):
url = 'https://www.kuaidaili.com/free/inha/{}/'.format(i)
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'}
response = requests.get(url,headers=header)
html1 = parsel.Selector(response.text)
h = html1.xpath('//table[@class="table table-bordered table-striped"]/tbody/tr')
for t in h:
ip_dict = {}
h2 = t.xpath('./td[4]/text()').extract_first()
h3 = t.xpath('./td[1]/text()').extract_first()
h4 = t.xpath('./td[2]/text()').extract_first()
# print(h2,h3,h4)
ip_dict[h2] = h3+':'+h4
ip_list.append(ip_dict)
time.sleep(0.5)
print(ip_dict)
爬取过程简单,先确定url,找到规律,利用循环爬取数据。用xpath来提取数据,并按照爬虫IP的格式建立字典,用列表存放字典。有一个小问题该网站有爬取速度限制,则可以通过time.sleep来控制爬取速度。
3.第二步:测试
在request方法中,可以通过proxies参数来伪装ip
可以先建立一个测试的函数,用这个IP去访问一个网站,如果得到快速反映,那么这个IP就可以使用。
代码如下
def check(list):
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'}
can = []
for i in list:
responses = requests.get('https://www.bilibili.com/',headers = header,proxies = i,timeout= 0.2)
if response.status_code == 200:
can.append(i)
return can
4.总结
构建IP池是学习爬虫必须的,通过proxies参数可以伪装Ip,小编能力有限,还无法利用数据库来存取IP池,只能通过列表的形式呈现给大家。
END
编 辑 | 王楠岚
责 编 | 王 曦