天天看点

4、Python爬虫中urllib库的相关介绍

4、Python爬虫中urllib库的相关介绍

*************** urllib 库相关介绍 ********************

官方文档地址:

https://docs.python.org/3/library/urllib.html

什么是urllib

urllib 是Python内置的HTTP请求库

包括以下模块:

urllib.request 请求模块

urllib.error 异常处理模块

urllib.parse url解析模块

urllib.robotparser.robots.txt 解析模块

*********************************************************

urlopen 方法:

关于 urllib.request.urlopen 参数的介绍

urllib.request.urlopen( url,

data = None,

[timeout,]*,

cafile = None,

capath = None,

cadefault = False,

context = None

)

============> urlopen 一般常用的有三个参数,它的参数如下:

urllib.request.urlopen(url,data,timeout)

*************实例代码

import urllib.request

url = "http://www.baidu.com"

response = urllib.request.urlopen(url)

print( response )

print( response.read() )

**************

response.read()可以获取到网页的内容,如果没有read(),将返回如下内容

<http.client.HTTPResponse object at 0x00000000029A4C88>

返回一个 HTTPResponse 对象

*********************************************************

data 参数的使用

这里通过http://httpbin.org/post 网站演示(该网站可以作为练习使用

urllib的一个站点使用,可以模拟各种请求操作)

*************实例代码

import urllib.parse

import urllib,request

data = bytes(urllib.parse.urlencode( {"word":"hello"} ), encoding = "utf-8" )

print(data)

# =========> 结果为 b'word=hello'

response = urllib.request.urlopen("http://httpbin.org/post", data = data)

print(response.read())

这里就用到了urll.parse,通过bytes(urllib.parse.urlencode()) 可以将post数据

进行转换放到urllib.request.urlopen的data参数中,这样就完成了一次post请求,

所以如果我们添加data参数的时候就是以post请求方式请求,如果没有data参数就是

get方式请求

*********************************************************

timeout 参数的使用

在某些网络情况不好或者服务端异常的情况下会出现请求慢的情况,或者请求

异常,所以这个时候我们需要给请求设置一个超时时间,而不是让程序一致等待结果

*************实例代码

import urllib.request

url = "http://www.baidu.com"

response = urllib.request.urlopen(url,timeout = 0.01)

print(response.status)

程序执行后,会出现报错,导致程序异常终止,并不是我们所希望的

***************timeout 参数代码优化

import urllib.request

import urllib.error

import socket

try:

response = urllib.request.urlopen("http://www.baidu.com",timeout = 0.01)

except urllib.error.URLError as e:

if isinstance(e.reason,socket.timeout):

print(" Time Out!!! ")

*********************************************************

request

设置 Headers

有很多网站为了防止爬虫爬网站造成网站瘫痪,会需要携带一些headers头部信息

才能访问,最常见的有 user-agent 参数

*************实例代码

import urllib.request

request = urllib.request.Request("https://python.org")

response = urllib.request.urlopen(request)

print(response.read().decode("utf-8"))

*************实例代码,添加请求头信息方式一

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" : "ceshi"

}

data = bytes(parse.urlencode(dict),encoding="utf-8")

req = request.Request(url = url, data = data ,headers = headers , method = "POST" )

response = request.urlopen(req)

print(response.read().edcode("utf-8"))

*************实例代码,添加请求头信息方式二

from urllib import request,parse

url = "http://httpbin.org/post"

dict = {

"name" : "ceshi"

}

data = bytes(parse.urlencode(dict),encoding="utf-8")

req = request.Request(url = url ,data = data ,method = "POST")

req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')

response = request.urlopen(req)

print(response.read().decode("utf-8"))

# 这种添加方式有个好处是自己可以定义一个请求头字典,然后循环进行添加

*********************************************************

代理,ProxyHandler

通过urllib.request.ProxyHandler() 可以设置代理,网站它会检测某一段时间某个IP的

访问次数,如果访问次数过多,它会禁止你的访问,所以这个时候需要通过设置代理来爬取数据

*************实例代码

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://htpbin.org/get")

print(response.read())

*********************************************************

cookie,HTTPCookieProcessor

cookie中保存了我们常见的登录信息,有时候爬取网站需要携带cookie信息访问,这里

用到了http.cookiejar,用于获取cookie以及存储cookie

***************实例代码

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)

同时cookie可以写入到文件中保存,有两种方式http.cookiejar.MozillaCookieJar 和

http.cookiejar.LWPCookieJar()

******************** 代码实例

import http.cookiejar ,urllib.request

filename = "cookie.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)

********************* 异常处理

在很多时候我们通过程序访问页面的时候,有的页面可能会出现错误,类似404,500等错误

这个时候需要我们捕获异常

from urll import request,error

try:

response = request.urlopen("http://pythonsite.com/1111.html")

except error.URLError as e:

print(e.reason)

上述代码访问一个不存在的页面,通过捕获异常,我们可以打印异常错误

这里我们知道的是urllib 异常有两个异常错误

URLError,HTTPError,

HTTPError是URLError的子类

URLError里只有一个属性:reason,即抓取异常的时候只能打印错误信息

HTTPError,里面有三个属性,code,reason,headers,即抓取异常的时候可以获得

code,reason,headers 三个信息

********************* 异常处理

from urllib import request,error

try:

response = request.urlopen("http://pythonsite.com/1111.html")

except error.HTTPError as e:

print(e.reason)

print(e.code)

print(e.headers)

except error.URLError as e:

print(e.reason)

else:

print("request.successfully")

******************************************** URL 解析 **********************

urlparse() ====》对地址进行拆分

urllib.parse.urlparse(urlstring,scheme="", allow_fragments = True )

功能一:

from urllib.parse import urlparse

result = urlparse("http://www.baidu.com/index.html;user?id=5#comment")

print(result)

运行结果:

ParseResult(scheme='http',

netloc='www.baidu.com',

path='/index.html',

params='user',

query='id=5',

fragment='comment'

)

该方法可以对传入的URL 地址进行拆分

*******************************************************************************

urlunparse() =======》该功能和urlparse的功能相反,它用于拼接

from urllib.parse import urlunparse

data = ["http","www.baidu.com","index.html","user","a=123","comment"]

print(urlunparse(data))

运行结果:

http://www.baidu.com/index.html;user?a=123#comment

*******************************************************************************

urljoin() 方法 ========》 URL拼接

from urllib.parse import urljoin

print(urljoin('http://www.baidu.com', 'FAQ.html'))

print(urljoin('http://www.baidu.com', 'https://pythonsite.com/FAQ.html'))

print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html'))

print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html?question=2'))

print(urljoin('http://www.baidu.com?wd=abc', 'https://pythonsite.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'))

从拼接的结果来看,拼接的时候后面的优先级高于前面的url

*******************************************************************************

urlencode() 方法 =========》 这个方法可以将字典转化为URL 参数

from urllib.parse import urlencode

params = {

"name":"ceshi",

"age":23

}

base_url = "http://www.baidu.com"

url = base_url + urlencode(params)

print(url)

可以将字典转化为URL参数信息

*******************************************************************************

下载图片的小代码(简单的,目前只能下载百度上图片专栏的图片,专业网站的收费图片不支持)

# 下载图片

import urllib.request

def download_image(image_url,filename):

image_url = input("请输入下载图片的链接地址: ")

filename = input("请输入保存图片的名称")

response = urllib.request.urlopen(image_url)

with open(filename + ".jpg", "wb") as fp:

fp.write(response.read())

return filename + ".jpg"

download_image("url","filename")

posted on 2019-02-27 11:53 stranger_ye 阅读(...) 评论(...) 编辑 收藏