Python爬虫——urllib_代理和代理池

  • 代理的常用功能:
  1. 突破自身IP访问限制,访问国外站点
  2. 访问一些单位或团体内部资源
  3. 提高访问速度
  4. 隐藏真实ip
  • 代码配置代理:
  1. 创建Request对象
  2. 创建ProxyHandler对象
  3. 用handler对象创建opender对象
  4. 使用 opender.open函数发送请求
import urllib.request

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

headers = {
    'User-Agent': ''
}

proxies = {
    'http': '123.456.789.123:1234'
}

request = urllib.request.Request(url, headers=headers)

handler = urllib.request.ProxyHandler(proxies)
opender = urllib.request.build_opener((handler))
response = opender.open(request)
content = response.read().decode('utf-8')

with open('files/daili.html', 'w', encoding='utf-8') as fp:
    fp.write(content)

代理池:代理池就是有代理IP组成的池子, 它可以提供多个稳定可用的代理IP

import urllib.request
import random

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

headers = {
    'User-Agent': ''
}

proxies_pool = [
    {'http': '123.456.789.123:1234'},
    {'http': '123.456.789.123:3456'},
    {'http': '123.456.789.123:5678'}
]

proxies = random.choice(proxies_pool)

request = urllib.request.Request(url, headers=headers)
# response = urllib.request.urlopen(request)

handler = urllib.request.ProxyHandler(proxies)
opender = urllib.request.build_opener((handler))
response = opender.open(request)
content = response.read().decode('utf-8')

with open('files/daili.html', 'w', encoding='utf-8') as fp:
    fp.write(content)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值