Python爬虫入门 ~ Handler处理器和代理服务器

349 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第19天,点击查看活动详情

前言

随着反爬技术的不断升级,定制的请求对象已经无法满足我们的业务需求,动态的cookie和代理无法通过请求对象的定制来生成,我们需要采用新的方式来实现。

Handler处理器

在前面的请求中我们是直接使用urlopen()的方式发起请求的,它并不能定制我们所需的请求头,现在要修改为可以定制请求头的handler方式,该方式共分为三步:

  1. 获取hanlder对象
  2. 获取opener对象
  3. 调用open方法

基本使用

import urllib.request

url = 'http://www.baidu.com'

headers = {
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}

request = urllib.request.Request(url=url, headers=headers)
hanlders = urllib.request.HTTPHandler()
opener = urllib.request.build_opener(hanlders)

response = opener.open(request)
print(response.read().decode('utf-8'))

image.png

代理服务器

什么是代理服务器?

代理服务器是一种重要的服务器安全功能,它的工作主要在开放系统互联(OSI)模型的会话层,从而起到防火墙的作用。

代理的常用功能

  1. 突破自身IP访问限制,访问国外站点。(翻墙,指绕过相应的IP封锁、内容过滤、域名劫持、流量限制等)
  2. 访问一些单位或团体内部资源
  3. 提高访问速度
  4. 隐藏真实IP

代码配置代理

  • 创建Request对象
  • 创建ProxyHandler对象
  • handler对象创建opener对象
  • 使用opener.open()函数发送请求

基本使用 使用ProxyHandler函数,传入代理服务器的ip和端口信息。

import urllib.request

url = 'https://www.baidu.com/s?wd=ip'

headers = {
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36',
}

proxies = {
    "http": '222.74.73.202:42055'
}

request = urllib.request.Request(url=url, headers=headers)
hanlders = urllib.request.ProxyHandler(proxies=proxies)
opener = urllib.request.build_opener(hanlders)

response = opener.open(request)
html = response.read().decode('utf-8')
print(html)

open = open('ip.html', 'w', encoding='utf-8')
open.write(html)

请求成功 image.png

当代理的ip请求频繁的时候,也会出现请求失败的情况,一般的代理都需要有一个ip池,防止单个ip请求频繁问题发生。 请求失败 image.png

简易版代理池

用列表保存所有的代理服务器配置,使用random函数可以随机得到其中一个,这样可以避免频繁使用同一个代理导致ip被封禁。

import random

proxies_pool = [
    {"http": '222.74.73.202:42055'},
    {"http": "183.236.232.160:8080"}
]

for i in range(1, 10):
    proxies = random.choice(proxies_pool)
    print(proxies)

image.png