爬虫爬取免费代理ip(附源码)

在爬取某些网站的时候我们有可能遇到ip反爬措施,通常可以使用代理ip的方法应对,本次我们要爬取的是国内某知名的代理ip网站,并挑选出其中响应速度符合我们要求的IP。
在这里插入图片描述

爬取代码如下:

def get_ip(last):
    proxies_list = []                   # ip池
    for page in range(1, last + 1):         # last为爬取的页数
        time.sleep(1)
        print(f'============正在爬取第{page}页数据=============')
        url = f'https://www.kuaidaili.com/free/inha/{page}/'
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0'
        }`在这里插入代码片`

        response = requests.get(url, headers=headers)
        response.encoding = response.apparent_encoding
        page_text = response.text

        # 正则匹配
        match = re.search(r'const fpsList = (\[.*?\]);', page_text).group()[16:-1]
        ip_list = json.loads(match)

        for ip in ip_list:
            ip_num = ip['ip']
            ip_port = ip['port']

            ip_proxy = ip_num + ':' + ip_port

            # 区分http和https,此处爬取的全为http
            proxy_dict = {
                'http': 'http://' + ip_proxy
            }
            proxies_list.append(proxy_dict)  # 加入ip池

    return proxies_list

检测ip是否可用:

def check_ip(proxies_list):
    time.sleep(1)
    can_use = []            # 可用ip池

    for ip in proxies_list:
        try:
            response = requests.get(url='https://www.baidu.com', proxies=ip, timeout=0.1)
            if response.status_code == 200:             # 可以访问则加入ip池
                can_use.append(ip)
        except:
            # print('当前代理:', ip, '请求超时,检验不合格')
            pass

    return can_use

以下附完整代码:

import json
import requests
import time
import re

# 测试ip是否可用

def check_ip(proxies_list):
    time.sleep(1)
    can_use = []            # 可用ip池

    for ip in proxies_list:
        try:
            response = requests.get(url='https://www.baidu.com', proxies=ip, timeout=0.1)
            if response.status_code == 200:             # 可以访问则加入ip池
                can_use.append(ip)
        except:
            # print('当前代理:', ip, '请求超时,检验不合格')
            pass

    return can_use

# 获取ip
def get_ip(last):
    proxies_list = []                   # ip池
    for page in range(1, last + 1):         # last为爬取的页数
        time.sleep(1)
        print(f'============正在爬取第{page}页数据=============')
        url = f'https://www.kuaidaili.com/free/inha/{page}/'
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0'
        }

        response = requests.get(url, headers=headers)
        response.encoding = response.apparent_encoding
        page_text = response.text

        # 正则匹配
        match = re.search(r'const fpsList = (\[.*?\]);', page_text).group()[16:-1]
        ip_list = json.loads(match)

        for ip in ip_list:
            ip_num = ip['ip']
            ip_port = ip['port']

            ip_proxy = ip_num + ':' + ip_port

            # 区分http和https,爬取的全为http
            proxy_dict = {
                'http': 'http://' + ip_proxy
            }
            proxies_list.append(proxy_dict)  # 加入ip池

    return proxies_list


def Get_ip(page):
    proxies_list = get_ip(page)  # 爬6页ip
    can_use = check_ip(proxies_list)  # 获得可用ip
    print(can_use)
    return can_use

if __name__ == '__main__':
    print('============正在开始爬取============')
    proxies_list = get_ip(6)                    # 爬6页ip
    print(proxies_list)
    print('============正在检测ip是否可用============')
    can_use = check_ip(proxies_list)            # 获得可用ip
    print(can_use)
  • 11
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫可以用来抓网络上的各种数据,包括大学排名信息。要大学排名,通常会涉及到网站的数据结构和反爬虫策略,这里是一个简化的步骤概述: 1. **目标选择**:确定要抓的具体大学排名数据来,如QS世界大学排名、泰晤士高等教育排名等官方网站。 2. **分析网页结构**:使用浏览器开发者工具(如Chrome的开发者工具)查看HTML码,理解数据是如何在页面上组织的,比如可能在`<table>`或`<div>`标签中。 3. **选择合适的库**:Python有许多库可用于爬虫,如BeautifulSoup、Scrapy或者更高级的Selenium(用于处理JavaScript渲染的内容)。对于简单的静态网页,BeautifulSoup通常足够。 4. **编写代码**:使用Python的requests库发送HTTP请求获页面内容,然后解析HTML文档提你需要的信息。例如,你可以查找特定的排名元素,如表格中的行或段落。 ```python import requests from bs4 import BeautifulSoup url = 'https://www.example.com/university-rankings' # 替换为实际的大学排名URL response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 查找特定的排名元素 rank_elements = soup.find_all('div', class_='rank-item') # 假设这些是包含排名的数据 ``` 5. **数据清洗和存储**:将提到的数据进行清洗,去掉无关的HTML标签,可能还需要处理缺失值和格式转换。可以保存到CSV、JSON或数据库中。 6. **处理反措施**:确保遵守网站的robots.txt文件,设置合理的User-Agent,可能需要使用代理IP或处理cookies和session,以防被网站封锁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值