本文介绍: 本博客介绍爬虫开发中常用的代理技术,并深入探讨代理IP的基础知识我们将讨论为何在爬虫使用代理,以及代理服务器的作用和类型。随后,我们介绍如何构建一个本地代理池,以便爬虫过程动态管理使用代理IP。我们分享相关的代码示例,涵盖代理池的搭建、代理IP的获取验证,以及如何在爬虫程序使用代理IP。通过本文,您将深入了解爬虫代理技术的重要性,掌握构建本地代理池的实践方法,并在实际开发中提升爬虫的稳定性和效率。无论您是初学者还是有一定经验的开发者本文都将为您提供有价值的指导和实用的代码示例
爬虫中代理的使用

在这里插入图片描述

爬虫中为何需要使用代理?

代理服务器可以根据其功能和使用方式分为以下几种类型

代理从哪里获得:

如何查询本地ip呢,网站http://httpbin.org/ip网页查看

在这里插入图片描述

import requests
from fake_useragent import UserAgent
ua = UserAgent()
url='http://httpbin.org/ip'
headers = {
    'User-Agent':ua.chrome
}
ip=requests.get(url,headers=headers).json()['origin']
print('本地ip:',ip)

在这里插入图片描述

代理模板

proxies={‘代理类型’:‘ip:port’}

proxies = {
    'http': '42.57.150.150:4278',
    'https': '42.57.150.151:4279',
    'ftp': '42.57.150.152:4280',
    # 添加更多协议和相应的代理
}
import requests
url = "你的目标网址"
headers = {"User-Agent": "你的用户代理"}
# 发送带有头部和代理的 GET 请求
page_text = requests.get(url=url, headers=headers, proxies=proxies)
# 现在,你可以通过 page_text.contentpage_text.text 等来访问响应内容

如果我请求是http ,但只有https,就会使用本机ip。

构建本地代理池:

根据代理IP提供的API构建本地代理池:

from bs4 import BeautifulSoup
from lxml import etree
import requests
import time
import random
headers = {
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}
url='http://http.tiqu.letecs.com/getip3?num=15&type=2&pro=&city=0&yys=0&port=1&pack=304028&ts=0&ys=0&cs=0&lb=6&sb=-&pb=4&mr=1&regions=&gm=4'
json_data = requests.get(url=url,headers=headers).json()

# "code":0,"data":[{"ip":"120.34.156.191","port":4234,"outip":"120.34.156.191"},{"ip":"27.29.156.55","port":4267,"outip":"27.29.156.55"}
#     ,{"ip":"60.17.154.30","p
json_list = json_data['data']
proxy_list = [] #代理池,每次请求,可以随机从代理池中选择一个代理来用
for dic in json_list:
    ip = dic['ip']
    port = dic['port']
    n_dic = {
        'https':ip+':'+str(port) # {'https':'111.1.1.1:1234'}
    }
    proxy_list.append(n_dic)
print(proxy_list)
proxies=random.choice(proxy_list)
print(proxies)

原文地址:https://blog.csdn.net/ak_bingbing/article/details/134700874

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_8321.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注