python爬蟲從入門到放棄(四)- Urllib庫的基本使用方法2

接着上一篇內容繼續學習Urllib庫


響應

響應類型、狀態碼、響應頭

import urllib.request

response = urllib.request.urlopen('https://www.python.org')
print(type(response))

可以看到結果爲:<class 'http.client.httpresponse'="">
我們可以通過response.status、response.getheaders().response.getheader("server"),獲取狀態碼以及頭部信息
response.read()獲得的是響應體的內容

當然上述的urlopen只能用於一些簡單的請求,因爲它無法添加一些header信息,如果後面寫爬蟲我們可以知道,很多情況下我們是需要添加頭部信息去訪問目標站的,這個時候就用到了urllib.request

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': 'zhaofan'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

添加請求頭的第二種方式

from urllib import request, parse

url = 'http://httpbin.org/post'
dict = {
    'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
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'))

這種添加方式有個好處是自己可以定義一個請求頭字典,然後循環進行添加

高級用法各種handler

代理,ProxyHandler

通過rulllib.request.ProxyHandler()可以設置代理,網站它會檢測某一段時間某個IP 的訪問次數,如果訪問次數過多,它會禁止你的訪問,所以這個時候需要通過設置代理來爬取數據

import urllib.request

proxy_handler = urllib.request.ProxyHandler({'http':'http://someproxy.com:8080' })
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('https://www.python.org/')
print(response.read())

cookie,HTTPCookiProcessor

cookie中保存中我們常見的登錄信息,有時候爬取網站需要攜帶cookie信息訪問,這裏用到了http.cookijar,用於獲取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(),當然你自己用哪種方式都可以

具體代碼例子如下:
http.cookiejar.MozillaCookieJar()方式

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)

http.cookiejar.LWPCookieJar()方式

import http.cookiejar, urllib.request
filename = 'cookie.txt'
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)

同樣的如果想要通過獲取文件中的cookie獲取的話可以通過load方式,當然用哪種方式寫入的,就用哪種方式讀取。

import http.cookiejar, urllib.request
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookie.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'))


獲取Cookie、保存、讀取本地cookie模擬登錄

import http.cookiejar, urllib.request
from urllib import parse
filename = 'cookie.txt'
postdata = bytes(parse.urlencode({'username':'yanhang','password':'23342321'}), encoding='utf8')
#聲明一個LWPCookieJar對象實例來保存cookie,之後寫入文件
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
#模擬登陸
response = opener.open('http://localhost:8080/frame/',postdata)
#寫入文件
cookie.save(ignore_discard=True, ignore_expires=True)
result = opener.open('http://localhost:8080/frame/console/index_new.jsp')
print(result.read())




異常處理

在很多時候我們通過程序訪問頁面的時候,有的頁面可能會出現錯誤,類似404,500等錯誤
這個時候就需要我們捕捉異常,下面先寫一個簡單的例子

from urllib import request,error

try:
    response = request.urlopen("http://pythonsite.com/1111.html")
except error.URLError as e:
    print(e.reason)

上述代碼訪問的是一個不存在的頁面,通過捕捉異常,我們可以打印異常錯誤

這裏我們需要知道的是在urllb異常這裏有兩個個異常錯誤:
URLError,HTTPError,HTTPError是URLError的子類

URLError裏只有一個屬性:reason,即抓異常的時候只能打印錯誤信息,類似上面的例子

HTTPError裏有三個屬性:code,reason,headers,即抓異常的時候可以獲得code,reson,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("reqeust successfully")

同時,e.reason其實也可以在做深入的判斷,例子如下:

import socket

from urllib import error,request

try:
    response = request.urlopen("http://www.pythonsite.com/",timeout=0.001)
except error.URLError as e:
    print(type(e.reason))
    if isinstance(e.reason,socket.timeout):
        print("time out")

URL解析

urlparse
The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.

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)

結果爲:

這裏就是可以對你傳入的url地址進行拆分
同時我們是可以指定協議類型:
result = urlparse("www.baidu.com/index.html;user?id=5#comment",scheme="https")
這樣拆分的時候協議類型部分就會是你指定的部分,當然如果你的url裏面已經帶了協議,你再通過scheme指定的協議就不會生效

urlunpars

其實功能和urlparse的功能相反,它是用於拼接,例子如下:

from urllib.parse import urlunparse

data = ['http','www.baidu.com','index.html','user','a=123','commit']
print(urlunparse(data))

結果如下

urljoin

這個的功能其實是做拼接的,例子如下:

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":"zhaofan",
    "age":23,
}
base_url = "http://www.baidu.com?"

url = base_url+urlencode(params)
print(url)

結果爲:


原文地址:http://www.cnblogs.com/zhaof/p/6910871.html

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