四、Python爬蟲中urllib庫的相關介紹

 

*************** urllib 庫相關介紹 ********************php

官方文檔地址:
https://docs.python.org/3/library/urllib.htmlhtml


什麼是urllibpython

urllib 是Python內置的HTTP請求庫cookie

包括如下模塊:
urllib.request 請求模塊
urllib.error 異常處理模塊
urllib.parse url解析模塊
urllib.robotparser.robots.txt 解析模塊網絡


*********************************************************socket

urlopen 方法:post

關於 urllib.request.urlopen 參數的介紹優化

urllib.request.urlopen( url,
data = None,
[timeout,]*,
cafile = None,
capath = None,
cadefault = False,
context = None
)網站

============> urlopen 通常經常使用的有三個參數,它的參數以下:ui

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

相關文章
相關標籤/搜索