爬虫(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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章