Python采集网站ip代理

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python采集网站ip代理

松鼠爱吃饼干   2022-05-23 我要评论

开发环境

Python 3.8

Pycharm

模块使用

requests >>> pip install requests

parsel >>> 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('<td data-title="IP">(.*?)</td>', response.text, re.S)
port_list = re.findall('<td data-title="PORT">(.*?)</td>', 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个,最后测试出只有一个是能用的,所以还是付费的好

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们