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

 

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