栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python采集网站ip代理, 检测IP代理是否可用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python采集网站ip代理, 检测IP代理是否可用

开发环境

Python 3.8Pycharm 模块使用

requests >>> pip install requestsparsel >>> pip install parsel 代理ip结构

proxies_dict = {
    "http": "http://" + ip:端口,
    "https": "http://" + ip:端口,
}
代码实现步骤: 1. 导入模块
# 导入数据请求模块
import requests  # 数据请求模块 第三方模块 pip install requests
# 导入 正则表达式模块
import re  # 内置模块
# 导入数据解析模块
import parsel  # 数据解析模块 第三方模块 pip install parsel  >>> 这个是scrapy框架核心组件
2. 发送请求, 对于目标网址发送请求 https://www.kuaidaili.com/free/
url = f'https://www.kuaidaili.com/free/inha/{page}/'  # 确定请求url地址
# 用requests模块里面get 方法 对于url地址发送请求, 最后用response变量接收返回数据
response = requests.get(url)
3. 获取数据, 获取服务器返回响应数据(网页源代码)
print(response.text)
4. 解析数据, 提取我们想要的数据内容

解析数据方式方法:

正则: 可以直接提取字符串数据内容xpath: 根据标签节点 提取数据内容css选择器: 根据标签属性提取数据内容

哪一种方面用那种, 那是喜欢用那种

正则表达式提取数据内容

正则提取数据 re.findall() 调用模块里面的方法
正则 遇事不决 .*? 可以匹配任意字符(除了换行符n以外) re.S

ip_list = re.findall('(.*?)', response.text, re.S)
port_list = re.findall('(.*?)', response.text, re.S)
print(ip_list)
print(port_list)
css选择器:

css选择器提取数据 需要把获取下来html字符串数据(response.text) 进行转换

# #list > table > tbody > tr > td:nth-child(1)
# //*[@id="list"]/table/tbody/tr/td[1]
selector = parsel.Selector(response.text) # 把html 字符串数据转成 selector 对象
ip_list = selector.css('#list tbody tr td:nth-child(1)::text').getall()
port_list = selector.css('#list tbody tr td:nth-child(2)::text').getall()
print(ip_list)
print(port_list)
xpath 提取数据
selector = parsel.Selector(response.text) # 把html 字符串数据转成 selector 对象
ip_list = selector.xpath('//*[@id="list"]/table/tbody/tr/td[1]/text()').getall()
port_list = selector.xpath('//*[@id="list"]/table/tbody/tr/td[2]/text()').getall()
提取ip
for ip, port in zip(ip_list, port_list):
    # print(ip, port)
    proxy = ip + ':' + port
    proxies_dict = {
        "http": "http://" + proxy,
        "https": "http://" + proxy,
    }
    print(proxies_dict)

5. 检测ip质量
try:
    response = requests.get(url=url, proxies=proxies_dict, timeout=1)
    if response.status_code == 200:
        print('当前代理IP: ', proxies_dict,  '可以使用')
        lis_1.append(proxies_dict)
except:
    print('当前代理IP: ', proxies_dict,  '请求超时, 检测不合格')


print('获取的代理IP数量: ', len(lis))
print('获取可用的IP代理数量: ', len(lis_1))
print('获取可用的IP代理: ', lis_1)

总共爬取了150个,最后测试出只有一个是能用的,所以还是付费的好

Python爬虫学习必备知识点:采集网站免费IP代理,并检测IP代理是否可用

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/714217.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号