数据获取—爬虫-2(Urllib包解析)

Urllib库

它是python内置的HTTP请求库,使用它发送Request。它主要包含以下几个基本模块:

  1. urllib.request:请求库,模拟打开网页的过程。
  2. urllib.error:异常处理模块,捕集,处理返回的错误值。
  3. urllib.parse:解析模块,提供了很多解析方法。
  4. urllib.roboparse:robots.txt文件解析,判断文件的可爬性。

Request

虽然urllib库是python的内置库,但是仍然需要导入。导入后可以直接使用urllib.request.urlopen()函数直接向服务器发送Request。Request中含有data数据时是POST请求,否则为GET请求。详细代码如下:

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)#urlopen函数形式,主要使用前三个参数   

#GET请求
import urllib.request #导入相应的库

response = urllib.request.urlopen('http://www.baidu.com') #发送Request
print(response.read().decode('utf-8')) '''打印相关请求,关于网页的编码格式如果常见的仍然无法编译,查看网页源代码,在head的第一行charset属性中可能会有相应信息。'''

# POST请求
import urllib.parse
import urllib.request

data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
#POST请求比GET多了一个data文件
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())

#设置延迟时间
import socket
import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)#反应时间0.1s
except urllib.error.URLError as e:
    if isinstance(e.reason, socket.timeout):#判断错误类型
        print('TIME OUT')

urlopen()能够发送Request,但是无法直接进行更多的设置,如设置请求头等。这时候可以先声明一个Request对象,然后传入相应的信息,最后将Request对象传入给urlopen().

from urllib import request, parse #导入相应的包

url = 'http://httpbin.org/post' #网址
headers = {
    'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
    'Host': 'httpbin.org'
} #设置请求头

dict = {
    'name': 'Germey'
}#设置DataFrom信息

data = bytes(parse.urlencode(dict), encoding='utf8')#将DataFrom信息编译成二进制流
req = request.Request(url=url, data=data, headers=headers, method='POST')#构建Request类
#如果req中缺少header时,urllib提供了add_header方法
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
response = request.urlopen(req)#传入urlopen
print(response.read().decode('utf-8'))#打印

Response

对于服务器发送的相应体,我们可以获取其类型、状态码和响应头。

import urllib.request

response = urllib.request.urlopen('https://www.python.org')
print(type(response))#获取相应类型
print(response.status)# 获取状态码
print(response.getheaders())#获取响应头
print(response.getheader('Server'))#获取相应头的中的参数
print(response.read().decode('utf-8'))#打印相应体

Handler

除了正常的Request内容之外,urllib提供很多附加功能,通常使用handler实现。

proxy

设置代理需要首先床架ProxyHandler,再将其构建为一个opener,使用open()方法打开。上文中urlopen()内部同样是构建一个opener,然后使用open()打开网页。

import urllib.request

proxy_handler = urllib.request.ProxyHandler({
    'http': 'http://127.0.0.1:9743',
    'https': 'https://127.0.0.1:9743'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://httpbin.org/get')
print(response.read())

Cookie用来维持网页登陆状态,用于爬取需要登陆的网站。常见的Cookie设置格式如下:

import http.cookiejar, urllib.request

cookie = http.cookiejar.CookieJar() #首先创建一个CookieJar类
handler = urllib.request.HTTPCookieProcessor(cookie)#借助handler处理Cookie
opener = urllib.request.build_opener(handler)#构建opener
response = opener.open('http://www.baidu.com')#打开网页
for item in cookie:
    print(item.name+"="+item.value)#打印出Cookie的值
	
import http.cookiejar, urllib.request
filename = "cookie.txt"
cookie = http.cookiejar.MozillaCookieJar(filename)#火狐浏览器格式存储cookie
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)#保存

import http.cookiejar, urllib.request
cookie = http.cookiejar.LWPCookieJar()#是用另一种格式存储
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)#加载Cookie
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))

异常处理

python中只定义了两种错误类,URLError和Base#Ear融入,厂用try--except,捕集判断错误类型。

from urllib import request, error
try:
    response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:
    print(e.reason)


from urllib import request, error

try:
    response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
    print(e.reason, e.code, e.headers, sep='
')
except error.URLError as e:
    print(e.reason)
else:
    print('Request Successfully')
	
import socket
import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('https://www.baidu.com', timeout=0.01)
except urllib.error.URLError as e:
    print(type(e.reason))
    if isinstance(e.reason, socket.timeout):
        print('TIME OUT')

URL解析

这就像一个工具包,里面有好多功能。

  1. urlparse:将URL分割,并生成一个ParseResult类,里面保存URL各部分信息。
#获取URl信息
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result)  
#设置URL信息,如有URL已经存在相应信息,那么该设置不会起作用
from urllib.parse import urlparse

result = urlparse('www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result)
#可以通过指定不存在相应信息方式更改切分结果
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments=False)#设置不存在allow_fragments
print(result)
  1. urlunparse:拼接一个URL
from urllib.parse import urlunparse

data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data))
  1. urljoin:合并一个URL,每个URL可以分为6个部分。该函数以后面的URl为基准使用前方URL中元素作为补充,得到性的URL。
from urllib.parse import urljoin

print(urljoin('http://www.baidu.com', 'FAQ.html'))
print(urljoin('http://www.baidu.com', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html?question=2'))
print(urljoin('http://www.baidu.com?wd=abc', 'https://cuiqingcai.com/index.php'))
print(urljoin('http://www.baidu.com', '?category=2#comment'))
print(urljoin('www.baidu.com', '?category=2#comment'))
print(urljoin('www.baidu.com#comment', '?category=2'))
  1. urlenconde:将字典形参数转化为GET请求参数,得到能够直接使用的URL。
from urllib.parse import urlencode

params = {
    'name': 'germey',
    'age': 22
}
base_url = 'http://www.baidu.com?'
url = base_url + urlencode(params)#拼接URL
print(url)
原文地址:https://www.cnblogs.com/lizhe-Ning/p/11373636.html