栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python爬虫-Handler处理器的基本使用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python爬虫-Handler处理器的基本使用

不积跬步,无以至千里;不积小流,无以成江海~

文章目录
  • 前言
  • 一、主要内容
  • 二、源码示例
    • 1.Handler的基本使用
    • 2.ip代理
    • 3 代理池的使用方法


前言

本篇文章通过举3个例子,来讲解Handler处理器的基本使用。


一、主要内容

例子1:示例Handler的基本使用
例子2:讲解ip代理
例子3:讲解代理池的使用方法

二、源码示例 1.Handler的基本使用

代码如下:

import urllib.request
url='http://www.baidu.com'
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
}
request=urllib.request.Request(url=url,headers=headers)
handler=urllib.request.HTTPHandler()                   #获取handler对象
opener=urllib.request.build_opener(handler)            #获取opener对象
response=opener.open(request)                          #调用open方法
content=response.read().decode('utf-8')
print(content)
2.ip代理

代码如下:
说明:代码中的url地址可自行更改;proxies中的https的值仅为示例,可自行按照格式来写自己的ip代理值。

import urllib.request
url='https://www.baidu.com/'
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
}
request=urllib.request.Request(url=url,headers=headers)
proxies={
    'https':'122.9.101.6:8888'
}
handler=urllib.request.ProxyHandler(proxies=proxies)   #获取handler对象
opener=urllib.request.build_opener(handler)            #获取opener对象
response=opener.open(request)                          #调用open方法
content=response.read().decode('utf-8')
with open('daili.html','w',encoding='utf-8') as fp:		#将文件下载到本地
   fp.write(content)
3 代理池的使用方法

该代码实现在代理池中随机选择一个ip来使用。

import urllib.request
import random
proxies_pool=[
    {'http':'118.24.219:8888'},
    {'http': '118.24.219:8889'},
    {'http': '118.24.219:8886'},
    {'http': '118.24.219:8881'}
]
proxies=random.choice(proxies_pool)

url='http://www.baidu.com'     
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
}
request=urllib.request.Request(url=url,headers=headers)
handler=urllib.request.ProxyHandler(proxies=proxies)
opener=urllib.request.build_opener(handler)
response=opener.open(request)
content=response.read().decode('utf-8')
with open('daili_1.html','w',encoding='utf-8') as fp:
    fp.write(content)   
   

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/920716.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号