requests爬取ip代理

本文介绍了如何确定爬取代理IP的需求,通过谷歌浏览器检查网络请求找到存储数据的URL,并利用requests库进行数据爬取。内容包括分析页面结构,获取数据URL以及爬取到的代理IP列表。
摘要由CSDN通过智能技术生成

1、确定需求,找到URL

现在很多网站给我们显示的页面是通过两个两个网页来显示的,因此会有两个URL

一个是页面框架,一个是里面的数据,我们可以用谷歌浏览器进入页面

=》右击=》检查=》选择network =》ctrl + f搜索页面中我们需要的数据(95.0.66.86)=》点击资源包 =》选择headers =》Request URL就是存储数据的URL

2、进行数据的爬取

import requests
import os
import time

start = time.time()         # 程序开始时间
def check_ip(proxies_list):
    # 检测代理的可用性
    can_use = []
    for proxy in proxies_list:
        try:
            response = requests.get(url='https://www.baidu.com',proxies=proxy,timeout=2)  # 等待时间
            if response.status_code == 200:
                can_use.append(proxy)
                print('当前代理:%s,---检测通过---' % proxy)
        except:
            print('当前代理:%s响应超时,不合格'%proxy)
    return can_use

proxy_list = [] # 接收爬取到的代理ip

# 判断文件是否存在
if not os.path.exists('D:/studySpider/proxys'):
    # 创建文件
    os.mkdir('D:/studySpider/proxys')

url = 'http://proxylist.fatezero.org/proxy.list'    # 准备好url
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'}  # 准备好请求头

response = requests.get(url=url,headers=headers).text   # 请求

li1 = response.split('\n')
count = 0
for d in li1[1:-1]:
    count += 1
    dict1 = eval(d)     # 字符串转字典
    host = str(dict1['host'])   # 获取host
    port = str(dict1['port'])   # 获取port
    type = dict1['type']        # 获取type
    proxy_dict = {type: host + ':' + port}  # 拼接为代理IP
    proxy_list.append(proxy_dict)       # 追加到列表proxy_list
    print('爬取ip代理 {0} 成功,第 {1} 个'.format(proxy_dict,count))
print(proxy_list)       # 输出代理列表
can_use = check_ip(proxy_list)  # 调用ip检测可用性

with open('D:/studySpider/proxys/proxy1.txt', "w") as f:    # 保存可用ip
    f.write('{0}'.format(can_use))
    f.close()       # 关闭文件
print('保存高质量代理成功:{0}'.format(can_use))
print('ip代理爬取成功,一共爬取 {0} 个,高质量代理 {1} 个 爬取时间 {2}秒'.format(count, len(can_use), time.time()-start))

爬取到的代理ip列表

[{'http': '64.225.8.192:80'}, {'http': '168.8.209.253:80'}, {'htt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>