Python爬虫笔记

python爬虫day-3

2019-04-08  本文已影响0人  南音木

个人学习笔记,方便自己查阅,仅供参考,欢迎交流

3.高级用法

更高级的操作(比如 Cookies 处理、代理理设置等)
工具Handler,可以把它理解为各种处理器,有专门处理登录验证,有处理 Cookies,有处理代理设置的。利用它们,我们几乎可以做到 HTTP请求中所有的事情。

urllib.reqest模块里的 BaseHandler

它是所有其他 Handler 的父类,它提供了最基本的方法,例如 default_ open()、 protocol_request ()等。
各种 Handler子类继承这个BaseHandler 类

比较重要类:OpenerDirector,可以称为 Opener

用法

1. 验证
有些网站在打开时就会弹出提示框,直接提示你输入用户名和密码,验证成功后才能查看页面。

from urllib.request import HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,build_opener
from urllib.error import URLError

username = 'username'
password = 'password'
url = 'http://localhost:5000/'
p = HTTPPasswordMgrWithDefaultRealm()
p.add_password(None,url,username,password)
auth_handler = HTTPBasicAuthHandler(p)
opener = build_opener(auth_handler)

try:
    result = opener.open(url)
    html = result.read().decode('utf-8')
    print(html)
except URLError as e:
    print(e.reason)

2. 代理

from urllib.error import URLError
from urllib.request import ProxyHandler,build_opener

proxy_handler = ProxyHandler({
        'http':'http://127.0.0.1:9743',
        'https':'http://127.0.0.1:9743'
})
opener = build_opener(proxy_handler)
try:
        response = opener.open('https://www.baidu.com')
        print(response.read().decode('utf-8'))
except URLError as e:
        print(e.reason)

3. Cookies

import http.cookiejar,urllib.request

cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
    print(item.name+"="+item.value)
filename = 'cookies.txt'
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True,ignore_expires = True)
filename = 'cookies.txt'
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True,ignore_expires = True)
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookies.txt',ignore_discard=True,ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))
上一篇 下一篇

猜你喜欢

热点阅读