Python实现IP代理批量采集的示例代码

Madeline ·
更新时间:2024-09-20
· 1548 次阅读

目录

开发环境 

模块使用 

基本流程(思路)

一. 数据来源分析

二. 代码实现步骤过程

代码

开发环境 

python 3.8

pycharm

模块使用 

import requests —> 需要安装 pip install requests

import parsel —> 需要安装 pip install parsel 解析数据模块

如果安装python第三方模块:

win + R 输入 cmd 点击确定, 输入安装命令 pip install 模块名 (pip install requests) 回车

在pycharm中点击Terminal(终端) 输入安装命令

IP代理: 采集网站数据, 采集比较快, 你被封IP <一段时间内容 不能访问这个网站>

基本流程(思路) 一. 数据来源分析

你要先分析, 你想要数据是请求那个url地址可以得到…

通过开发者工具抓包分析, 分析我们想要数据来源

I. F12或者鼠标右键点检查 选择network 刷新网页

II. 分析数据内容 <IP 以及 端口>来自于哪里

通过开发者工具 关键字搜索数据来源 找到相对应的数据包

二. 代码实现步骤过程

爬虫基本四大步骤

发送请求, 模拟浏览器对于分析得到url地址发送请求 https://free.kuaidaili.com/free/inha/1/

获取数据, 获取服务器返回响应数据 —> 开发者工具里面看到 response

解析数据, 提取我们想要数据内容

保存数据, 我们想要数据内容保存本地

代码 # 导入数据请求模块 ---> 第三方模块, 需要安装 在cmd里面 pip install requests import requests # 导入数据解析模块 ---> 第三方模块, 需要安装 在cmd里面 pip install parsel import parsel # 导入json模块 ---> 内置模块 不需要安装 import json # 1. 发送请求, 模拟浏览器对于分析得到url地址发送请求 proxies_list = [] proxies_list_1 = [] # 请求url地址 for page in range(1, 11): url = f'https://www.boc.cn/sourcedb/whpj/index_{page}.html' """ headers请求头, 模拟伪装浏览器去发送请求 不加headers相当于裸奔 ----> 告诉服务器, 我是爬虫 我是爬虫~ 你来抓我~ 加什么东西, 在哪加 ---> 开发者工具里面 复制 ua """ headers = { # User-Agent 用户代理 表示浏览器基本身份标识 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36' } # 发送请求 ---> <Response [200]> 响应对象, 200状态码 表示请求成功 response = requests.get(url=url, headers=headers) # 2. 获取数据, 获取服务器返回响应数据 print(response.text) """ 3. 解析数据, 提取我们想要数据内容 解析方法: re正则: 对于字符串数据进行提取 css: 根据标签属性内容提取 xpath: 根据标签节点提取 """ # 转换数据类型 response.text<字符串数据> <Selector xpath=None data='<html>\n<head>\n<meta http-equiv="X-UA-...'> selector = parsel.Selector(response.text) # 获取tr标签 ---> 返回列表 列表里面元素是 Selector对象 trs = selector.css('#list table tbody tr') trs_1 = selector.xpath('//*[@id="list"]/table/tbody/tr') # for循环 一个一个提取tr标签 for tr in trs: # 提取ip号 td:nth-child(1)::text 获取第一个td标签里面文本数据 ip_num = tr.css('td:nth-child(1)::text').get() # ip_num_1 = tr.xpath('td[1]/text()').get() ip_port = tr.css('td:nth-child(2)::text').get() """ IP代理结构是什么样子的? proxies_dict = { "http": "http://" + ip:端口, "https": "http://" + ip:端口, } """ proxies_dict = { "http": "http://" + ip_num + ':' + ip_port, "https": "https://" + ip_num + ':' + ip_port, } proxies_list_1.append(proxies_dict) # 检测IP代理是否可用 用这个代理去请求一下网站就好了 try: response_1 = requests.get(url='https://www.baidu.com/', proxies=proxies_dict, timeout=1) if response_1.status_code == 200: proxies_list.append(proxies_dict) print('代理可以使用: ', proxies_dict) # 保存代理到文本 with open('代理.txt', mode='a', encoding='utf-8') as f: f.write(json.dumps(proxies_dict)) f.write('\n') except: print('当前代理:', proxies_dict, '请求超时, 检测不合格') print('===' * 50) print('一共获取到:', len(proxies_list_1)) print('可以使用代理: ', len(proxies_list)) print(proxies_list)

到此这篇关于Python实现IP代理批量采集的示例代码的文章就介绍到这了,更多相关Python采集IP代理内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



ip 示例 ip代理 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号