python爬虫第1章 urllib库(一) urllib库概述

python爬虫第1章 urllib库(一) urllib库概述

urllib是一个模拟浏览器发送请求的库,是python内置的库,不需要额外的安装。

python2中分为:urllib urllib2

python3中被合并为urllib,urllib.request、urllib.parse分别对应于urllib、urllib2。

在python3中分成了三个模块:

  1. urllb.request 请求模块
  2. urllib.parse 解析模块
  3. urllib.error 异常处理模块

一、urllib.request模块

该模块中的主要方法:

方法 示例
urllib.request.urlopen response = urllib.request.urlopen(r"https://www.baidu.com") # 传入url,得到HTTPResponse响应对象
urllib.request.urlretrieve urllib.request.urlretrieve(r"https://www.baidu.com", “baidu.html”) # 传入url、文件路径,直接将响应数据保存在本地

响应对象response(http.client.HTTPResponse对象)的主要方法:

方法 描述
response.read() 读取响应体,内容是字节类型 。可通过response.read().decode()转为字符串
response.geturl() 获取请求的url
response.getheaders() 获取头部信息,是列表。可通过dict(list1) 转为字典以便取值
response.getcode() 获取响应状态码
response.readlines() 按行读取,返回列表,都是字节类型

(一)urllib.request.urlopen方法示例

import urllib.request

url = r"https://www.baidu.com"
response = urllib.request.urlopen(url)

print(response) # 打印:<http.client.HTTPResponse object at 0x00000219BC7B56A0>

print(response.read()) # 打印二进制

print(response.read().decode()) # 将二进制转为字符串进行打印

# 将响应数据写入文件
with open("baidu.html","w",encoding="utf-8") as f:
    f.write(response.read().decode())
#注意:response.read()只能读取一次,第二次就读取不到了

(二)urlopen和urlretrieve异同:以下载一张图片为例

import urllib.request

url =r"https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_86d58ae1.png"

response  = urllib.request.urlopen(url)

with open("chushiyan.jpg","wb") as f:
    f.write(response.read())
import urllib.request

url = r"https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_86d58ae1.png"

urllib.request.urlretrieve(url, "chushiyan1.jpg")

从上面案例看出,同样下载一张图片,urlretrieve方法更简洁一些。

二、urllib.parse模块

url只能由特定的字符组成:字母、数字、下划线。如果出现其他的,如:$、空格、汉字等,就要进行编码。urllib.parse模块就是干这个的。

(一)主要方法

方法 描述
urllib.parse.quote(url) url编码。注:quote v.引述;举证 n. 引用
urllib.parse.unquote(url) url解码
urllib.parse.urlencode(dict2) 传入一字典,将字典拼接为url查询部,并完成url编码

(二)主要方法的使用示例

1、urllib.parse.quote()和urllib.parse.unquote()

import urllib.parse
url = r"http://www.baidu.com/index.html?name=张三&password=123456"

# 1、url编码
url = urllib.parse.quote(url)
print(url)
# 输出:http%3A//www.baidu.com/index.html%3Fname%3D%E5%BC%A0%E4%B8%89%26password%3D123456

# 2、url解码
print(urllib.parse.unquote(url))
# 输出:http://www.baidu.com/index.html?name=张三&password=123456

2、urllib.parse.urlencode()

先看看,不使用urllib.parse.urlencode()时,如何对参数组成的字典进行url编码:

import urllib.parse
url = r"http://www.baidu.com"

date = {
    "name":"张三",
    "age":25,
    "gender":"nan",
    "stature":175
}
list2 = []
for k,v in date.items():
    list2.append(k+"="+str(v))

query_string = "&".join(list2)

url = url + "?"+query_string;
url = urllib.parse.quote(url)

print(url)

使用urlencode()函数时:

import urllib.parse
url = r"http://www.baidu.com"

date = {
    "name":"张三",
    "age":25,
    "gender":"nan",
    "stature":175
}

query_string = urllib.parse.urlencode(data)

url = url + "?" +query_string

print(url)

输出同样的结果:

http%3A//www.baidu.com%3Fname%3D%E5%BC%A0%E4%B8%89%26
age%3D25%26gender%3Dnan%26stature%3D175

(三)综合案例

案例:让用户输入需要搜索的关键字,下载保存该搜索结果页面。

百度搜索的url示例:http://www.baidu.com/s?wd=chushiyan

import urllib.request
import urllib.parse

word = input("请输入您需要搜索的内容...")
url = r"http://www.baidu.com/s?"

data= {
    "wd":word
}

query_string = urllib.parse.urlencode(data)
url +=  query_string

urllib.request.urlretrieve(url,word+".html")

三、urllib.error模块

异常类:URLError、HTTPError。前者是后者的父类。都位于urllib.error模块中(error.py文件)。

发生URLError异常的情况:

(1)没有网络

(2)服务器连接失败

(3)找不到指定的服务器

HTTPError异常:

HTTP 错误可能是“404 Page Not Found”、“500 Internal Server Error”等。所有类似情形, urlopen 函数都会抛出“HTTPError”异常。

注:两个异常同时捕获时,需要将HTTPError写在前面,URLError写在后面。

import urllib.request
import urllib.parse
import urllib.error

# 定义一个不存在的url
url = r"http://chushiyan.org"

try:
    response = urllib.request.urlopen(url)
    print(response)

except urllib.error.HTTPError as e:
    print(e)
except urllib.error.URLError as e:
    print(e) #打印:<urlopen error [Errno 11001] getaddrinfo failed>

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