爬取快代理免费ip,构建自己的代理ip池,不再怕反爬(附代码) 松鼠爱吃饼干

我们在做爬虫的过程中经常会遇到这样的情况:最初爬虫正常运行,正常抓取数据,然而一杯茶的功夫可能就会出现错误,比如403 Forbidden;这时候网页上可能会出现“您的IP访问频率太高”这样的提示,过很久之后才可能解封,但是一会后又出现这种情况。

因此我们使用某种方式来伪装本机IP,以使服务器无法识别由本地计算机发起的请求,这样我们可以成功地阻止IP被封。所以这时候代理ip就派上用场了。

爬虫的一般思路

1、确定爬取的url路径,headers参数

2、发送请求 -- requests 模拟浏览器发送请求,获取响应数据

3、解析数据 -- parsel 转化为Selector对象,Selector对象具有xpath的方法,能够对转化的数据进行处理

4、保存数据

[环境介绍]:

python 3.6

pycharm

requests

parsel(xpath)

扫描二维码关注公众号,回复: 11139531 查看本文章

代码如下:

import requests
import parsel
import time

def check_ip(proxies_list):
    """检测ip的方法"""
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}

    can_use = []
    for proxy in proxies_list:
        try:
            response = requests.get('http://www.baidu.com', headers=headers, proxies=proxy, timeout=0.1)  # 超时报错
            if response.status_code == 200:
                can_use.append(proxy)
        except Exception as error:
            print(error)
    return can_use
import requests
import parsel

# 1、确定爬取的url路径,headers参数
base_url = 'https://www.kuaidaili.com/free/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}

# 2、发送请求 -- requests 模拟浏览器发送请求,获取响应数据
response = requests.get(base_url, headers=headers)
data = response.text
# print(data)

# 3、解析数据 -- parsel  转化为Selector对象,Selector对象具有xpath的方法,能够对转化的数据进行处理
# 3、1 转换python可交互的数据类型
html_data = parsel.Selector(data)
# 3、2 解析数据
parse_list = html_data.xpath('//table[@class="table table-bordered table-striped"]/tbody/tr') # 返回Selector对象
# print(parse_list)

# 免费 IP  {"协议":"IP:port"}
# 循环遍历,二次提取
proxies_list = []
for tr in parse_list:
    proxies_dict = {}
    http_type = tr.xpath('./td[4]/text()').extract_first()
    ip_num = tr.xpath('./td[1]/text()').extract_first()
    port_num = tr.xpath('./td[2]/text()').extract_first()
    # print(http_type, ip_num, port_num)

    # 构建代理ip字典
    proxies_dict[http_type] = ip_num + ':' + port_num
    # print(proxies_dict)
    proxies_list.append(proxies_dict)

print(proxies_list)
print("获取到的代理ip数量:", len(proxies_list), '个')

调用ip

# 检测代理ip可用性
can_use = check_ip(proxies_list)
print("能用的代理:", can_use)
print("能用的代理数量:", len(can_use))

效果如下:

如果你处于想学Python或者正在学习Python,Python的教程不少了吧,但是是最新的吗?说不定你学了可能是两年前人家就学过的内容,在这小编分享一波2020最新的Python教程。获取方式,私信小编 “ 资料 ”,即可免费获取哦!
 

发布了141 篇原创文章 · 获赞 91 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46614154/article/details/105750496