Python   发布时间:2022-04-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Python采集网站ip代理, 检测IP代理是否可用大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

开发环境

  • 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)

 

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

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)

 

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

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

大佬总结

以上是大佬教程为你收集整理的Python采集网站ip代理, 检测IP代理是否可用全部内容,希望文章能够帮你解决Python采集网站ip代理, 检测IP代理是否可用所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: