爬虫(cookie,代理IP)

1.先登录得到url 和cookie

import urllib.request

url="https:***"
headers={
    "Host           ":"blog.csdn.net" ,
    "Connection     ":"keep-alive" ,
    # "Cache-Control  ":"max-age=0" ,
    "User-Agent     ":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36" ,
    "Accept         ":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" ,
    "Referer        ":"https :****" ,
    "Accept-Language":"zh-CN,zh;q=0.9" ,
    "Cookie         ":"*******"

}
request=urllib.request.Request(url,headers=headers)
response=urllib.request.urlopen(request)
html=response.read()
html=html.decode('utf-8')
print(html)

2.opener 是urllib2.OpenerDirector的实例,我们之前一直都在使用的urlopen,它是一个特殊的opener(也就是模块帮我们构建好的).

但是基本的urlopen()方法不支持代理,cookie等其他的HTTP/HTTPS高级功能.所以要支持这些功能

  • 使用相关的Handler处理器,创建特定功能的处理对象
  • 然后通过urllib.request.build_opener()的方法使用这些处理器对象,创建自定义opener对象
  • 使用自定义的opener对象,调用open()方法发送请求

如果程序里所有的请求都是用自定义的opener,可以使用urllib.request.install_opener()将自定义的opener对象定义为全局,表示如果之后凡是调用urlopen,都将使用opener()根据需求来选择

开放代理与私密代理的使用

import urllib.request

#代理开关
from urllib.request import ProxyHandler

proxyswitch=True

#构建一个Handler处理对象,参数是一个字典类型,包括代理类型和代理服务器IP+PROT
httpproxy_handler=ProxyHandler({"http":"****"})
#独享私密代理
# httpproxy_handler=ProxyHandler({"http":"用户名:密码@114.215.95.188:端口号"})

#构建了一个没有代理的处理对象
nullproxy_handler=ProxyHandler({})

if proxyswitch:
    opener=urllib.request.build_opener(httpproxy_handler)
else:
    opener=urllib.request.build_opener(nullproxy_handler)

#构建一个全局的opener,之后的所有请求都可以用urlopen()方式去发送,也附带handler的功能
urllib.request.install_opener(opener)
request=urllib.request.Request('http://www.baidu.com/')
response=urllib.request.urlopen(request)
html=response.read()


print(html)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值