25python成功输出第一个66免费ip代理

# -*- coding:UTF-8 -*-
from bs4 import BeautifulSoup
# from selenium import webdriver
import subprocess as sp
from lxml import etree
import requests
import random
import re

   #requests的Session可以自动保持cookie,不需要自己维护cookie内容
S = requests.Session()
   #西祠代理高匿IP地址
target_url = 'http://www.66ip.cn/areaindex_15/1.html'
   #完善的headers
target_headers = {'Upgrade-Insecure-Requests':'1',
   'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
   'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
   'Referer':'http://www.66ip.cn/areaindex_15/1.html',
   'Accept-Encoding':'gzip, deflate, sdch',
   'Accept-Language':'zh-CN,zh;q=0.8',
}
   #get请求
target_response = S.get(url = target_url, headers = target_headers)
   #utf-8编码
target_response.encoding = 'utf-8'
   #获取网页信息
target_html = target_response.text
   #获取id为ip_list的table

bf1_ip_list = BeautifulSoup(target_html, 'lxml')




bf2_ip_list = BeautifulSoup(str(bf1_ip_list.find_all(id='footer')), 'lxml')
ip_list_info = bf2_ip_list.table.contents

# 存储代理的列表
proxys_list = []
# 爬取每个代理信息
for index in range(len(ip_list_info)):
    if index % 2 == 1 and index != 1:
        dom = etree.HTML(str(ip_list_info[index]))
        ip = dom.xpath('//td[1]')
        port = dom.xpath('//td[2]')
        protocol = dom.xpath('//td[3]')
        proxys_list.append('http://' + '#' + ip[0].text + '#' + port[0].text)
        print(proxys_list)
# 返回代理列表
### 安装和配置IP2Region库 要在 Python 中安装并配置 IP2Region 库,可以按照以下方法操作: #### 1. 安装依赖项 首先需要确保已安装 `pip` 工具来管理 Python 的第三方包。如果尚未安装该工具,请先完成安装。 通过 pip 命令安装 ip2region-python 绑定模块: ```bash pip install py-ip2region ``` 此命令会自动下载并安装最新版本的 Py-ip2region 模块[^4]。 #### 2. 下载数据文件 为了使 IP 查询功能正常工作,还需要准备对应的数据库文件 (`ip2region.db`)。可以从官方仓库获取预编译的数据文件或者自行构建。 推荐直接从 GitHub 或者其他镜像站点下载最新的二进制版 DB 文件至本地路径下,例如 `/path/to/your/project/data/ip2region.db`。 #### 3. 编写测试脚本 创建一个简单的 Python 测试程序用于验证环境搭建是否成功以及熟悉 API 使用方式: 以下是基于给定示例的一个完整例子: ```python from ip2region import Ip2Region def query_ip_region(ip_address): """Query the regional information of an IP address.""" searcher = Ip2Region("/absolute/path/to/ip2region.db") # 替换为实际存储位置 data = searcher.memorySearch(ip_address) return f"{data['city_id']}|{data['region'].decode('utf-8')}" if __name__ == "__main__": sample_ips = ['66.249.82.86', '101.108.251.187'] for ip in sample_ips: res = query_ip_region(ip) print(f"The location info for {ip} is: {res}") ``` 上述代码展示了如何加载指定路径下的 `.db` 数据源并通过内存模式快速查找目标 IP 所属地区信息[^3]^, ^[^2]. 注意:在生产环境中建议采用更安全的方式处理敏感资源访问权限等问题;另外考虑到性能因素可以选择不同的搜索策略比如 B 树索引等优化手段提升效率[^1]. ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值