Python3学习-urllib库详解

Python3学习-urllib库详解

    • 网站身份验证
    • 代理
    • cookies
    • 异常处理
    • 链接解析
    • Robots协议

本文内容参考崔庆才童鞋的《Python 3网络爬虫开发实战》,就当做一个读书笔记吧,以后自己写代码的时候可以多翻翻自己以前学过的,不过程序真的几天不写就手生啊啊啊啊。以后编程不能停呀!

网站身份验证

利用HTTPBasicAuthHandler进行身份验证

// An highlighted block
from urllib.request import HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,build_opener
from urllib.error import URLError
username='username'
password='password'
url='http://www.baidu.com/'#网址
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)

代理

添加代理的方法

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

cookies

输出网站上的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)

输出Mozilla型浏览器的Cookies格式

import http.cookiejar,urllib.request

filename='cookies.txt'
cookie=http.cookiejar.MozillaCookieJar(filename)
#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)

利用LWP格式Cookies爬取网站

import http.cookiejar,urllib.request

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'))

异常处理

URLError类来自于urllib库里的error模块,是error异常模块的基类。由request模块产生的异常都可以通过捕获这个类来处理。
HTTPError类是URLError的子类,专门用来处理HTTP请求错误,有三个属性。

from urllib import request,error
try:
	response=request.urlopen('https//www.baidu.com/')
except error.HTTPError as e:
	print(e.reason,e.code,e.headers,seq='\n')
except error.URLError as e:
	print(e.reason)
else:
	print('Request Successfully')

链接解析

1.urlparse(urlstring,scheme=’’,allow_fragments=True)可以实现URL的识别和分段,一个标准的链接格式是scheme://netloc/path;params?query#fragment
scheme:协议
netloc:域名
path:访问路径
params:参数
query:查询条件
fragment:锚点。直接定位页面内部的下拉位置

from urllib import request,error
try:
	response=request.urlopen('https//www.baidu.com/',timeout=0.01)
except error.HTTPError as e:
	print(e.reason,e.code,e.headers,seq='\n')

2.**urlunparse()**构造URL,接受的蚕食是一个可迭代对象,长度必须为6。
3.**urlsplit()**和urlparse类似,只是params部分合并到path中。
4.**urlunsplit()**将链接的各个部分组合成完整链接,传入的参数是个可迭代的对象,长度必须是5
5.urljoin提供一个基础链接作为第一个参数,将新的链接作为第二个参数,该方法会分析base_url的scheme、netloc和path这3个内容。

from urllib.parse import urljoin
print(urljoin('http://www.baidu.com','FAQ.html'))

6.**urlencode()**构造GET请求参数

from urllib.parse import urlencode
params={
	'name':'germey'
	'age':22
}
base_url='http://www.baidu.com'
url=base_url+urlencode(params)#将字典类型转换为请求参数
print(url)

7.**parse_qs()**将GET请求参数转变回字典
8.**parse_qsl()**用于将参数转换为元组组成的列表
9.**quote()**将内容转化为URL编码的格式,URL中带有中文参数时,可以使用这个方法避免乱码问题

from urllib.prase import quote
keyword='太阳'
url='http://www.baidu.com/s?wd='+quote(keyword)
print(url)

10.**unquote()**进行URL解码

Robots协议

Robots协议也称作爬虫协议,全名为网络爬虫排除标准(Robots Exclusion Protocol),用来告诉爬虫和搜索引擎哪些页面可以抓取,哪些不可以抓取,通常是一个叫做robots.txt的文本文件,一般放在网站的根目录下。
禁止所有爬虫访问网站某些目录:

User-agent:*
Disallow:/private/
Disallow:/tmp/

1.robotparser模块,解析robot.txt文件
urllib.robotparser.RobotFileParser(url=’ ')或者set_url(),接下来举个栗子

from urllib.robotFileParser import RobotFileParser
rp=RobotFileParser()
rp.set_url('http://wwww.jianshu.com/robot.txt')
rp.read()
#rp.parser(urlopen('http://www.jianshu.com/robot.txt').read().decode('utf-8').split('\n'))
print(rp.can_fetch('*','http://www.jianshu.com/p/b67554025d7d'))

你可能感兴趣的:(Python3学习)