Python數(shù)據(jù)分析與挖掘之urllib框架的基本使用

什么是urllib

urllib是Python內(nèi)置的HTTP請(qǐng)求庫(kù)

包括以下幾個(gè)模塊

  • urllib.request 請(qǐng)求模塊
  • urllib.error 異常處理模塊
  • urllib.parse url解析模塊
  • urllib.robotparser robots.txt解析模塊

urlopen

關(guān)于urllib.request.urlopen參數(shù)的介紹:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

url參數(shù)的使用

先寫(xiě)一個(gè)簡(jiǎn)單的例子:

import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))

urlopen一般常用的有三個(gè)參數(shù),它的參數(shù)如下:
urllib.requeset.urlopen(url,data,timeout)
response.read()可以獲取到網(wǎng)頁(yè)的內(nèi)容,如果沒(méi)有read(),將返回如下內(nèi)容

data參數(shù)的使用

上述的例子是通過(guò)請(qǐng)求百度的get請(qǐng)求獲得百度,下面使用urllib的post請(qǐng)求
這里通過(guò)http://httpbin.org/post網(wǎng)站演示(該網(wǎng)站可以作為練習(xí)使用urllib的一個(gè)站點(diǎn)使用,可以
模擬各種請(qǐng)求操作)。

import urllib.parse
import urllib.request

data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
print(data)
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())

這里就用到urllib.parse,通過(guò)bytes(urllib.parse.urlencode())可以將post數(shù)據(jù)進(jìn)行轉(zhuǎn)換放到urllib.request.urlopen的data參數(shù)中。這樣就完成了一次post請(qǐng)求。
所以如果我們添加data參數(shù)的時(shí)候就是以post請(qǐng)求方式請(qǐng)求,如果沒(méi)有data參數(shù)就是get請(qǐng)求方式

timeout參數(shù)的使用

在某些網(wǎng)絡(luò)情況不好或者服務(wù)器端異常的情況會(huì)出現(xiàn)請(qǐng)求慢的情況,或者請(qǐng)求異常,所以這個(gè)時(shí)候我們需要給
請(qǐng)求設(shè)置一個(gè)超時(shí)時(shí)間,而不是讓程序一直在等待結(jié)果。例子如下:

import urllib.request

response = urllib.request.urlopen('http://httpbin.org/get', timeout=1)
print(response.read())

運(yùn)行之后我們看到可以正常的返回結(jié)果,接著我們將timeout時(shí)間設(shè)置為0.1
運(yùn)行程序會(huì)提示如下錯(cuò)誤

URLError: <urlopen error timed out>

所以我們需要對(duì)異常進(jìn)行抓取,代碼更改為

import socket
import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason, socket.timeout):
        print('TIME OUT')

響應(yīng)

響應(yīng)類型、狀態(tài)碼、響應(yīng)頭

import urllib.request

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

可以看到結(jié)果為:

<class 'http.client.httpresponse'="">
我們可以通過(guò)response.status、response.getheaders().response.getheader("server"),獲取狀態(tài)碼以及頭部信息
response.read()獲得的是響應(yīng)體的內(nèi)容

當(dāng)然上述的urlopen只能用于一些簡(jiǎn)單的請(qǐng)求,因?yàn)樗鼰o(wú)法添加一些header信息,如果后面寫(xiě)爬蟲(chóng)我們可以知道,很多情況下我們是需要添加頭部信息去訪問(wèn)目標(biāo)站的,這個(gè)時(shí)候就用到了urllib.request

request

設(shè)置Headers

有很多網(wǎng)站為了防止程序爬蟲(chóng)爬網(wǎng)站造成網(wǎng)站癱瘓,會(huì)需要攜帶一些headers頭部信息才能訪問(wèn),最長(zhǎng)見(jiàn)的有user-agent參數(shù)

寫(xiě)一個(gè)簡(jiǎn)單的例子:

import urllib.request

request = urllib.request.Request('https://python.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

給請(qǐng)求添加頭部信息,從而定制自己請(qǐng)求網(wǎng)站是時(shí)的頭部信息

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

添加請(qǐng)求頭的第二種方式

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

這種添加方式有個(gè)好處是自己可以定義一個(gè)請(qǐng)求頭字典,然后循環(huán)進(jìn)行添加

高級(jí)用法各種handler

代理,ProxyHandler

通過(guò)rulllib.request.ProxyHandler()可以設(shè)置代理,網(wǎng)站它會(huì)檢測(cè)某一段時(shí)間某個(gè)IP 的訪問(wèn)次數(shù),如果訪問(wèn)次數(shù)過(guò)多,它會(huì)禁止你的訪問(wèn),所以這個(gè)時(shí)候需要通過(guò)設(shè)置代理來(lái)爬取數(shù)據(jù)

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,HTTPCookiProcessor

cookie中保存中我們常見(jiàn)的登錄信息,有時(shí)候爬取網(wǎng)站需要攜帶cookie信息訪問(wèn),這里用到了http.cookijar,用于獲取cookie以及存儲(chǔ)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)

同時(shí)cookie可以寫(xiě)入到文件中保存,有兩種方式http.cookiejar.MozillaCookieJar和http.cookiejar.LWPCookieJar(),當(dāng)然你自己用哪種方式都可以

具體代碼例子如下:
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)

同樣的如果想要通過(guò)獲取文件中的cookie獲取的話可以通過(guò)load方式,當(dāng)然用哪種方式寫(xiě)入的,就用哪種方式讀取。

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

異常處理

在很多時(shí)候我們通過(guò)程序訪問(wèn)頁(yè)面的時(shí)候,有的頁(yè)面可能會(huì)出現(xiàn)錯(cuò)誤,類似404,500等錯(cuò)誤
這個(gè)時(shí)候就需要我們捕捉異常,下面先寫(xiě)一個(gè)簡(jiǎn)單的例子

from urllib import request,error

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

上述代碼訪問(wèn)的是一個(gè)不存在的頁(yè)面,通過(guò)捕捉異常,我們可以打印異常錯(cuò)誤

這里我們需要知道的是在urllb異常這里有兩個(gè)個(gè)異常錯(cuò)誤:
URLError,HTTPError,HTTPError是URLError的子類

URLError里只有一個(gè)屬性:reason,即抓異常的時(shí)候只能打印錯(cuò)誤信息,類似上面的例子

HTTPError里有三個(gè)屬性:code,reason,headers,即抓異常的時(shí)候可以獲得code,reson,headers三個(gè)信息,例子如下:

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

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

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)

結(jié)果為:

ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')

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

urlunpars

其實(shí)功能和urlparse的功能相反,它是用于拼接,例子如下:

from urllib.parse import urlunparse

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

結(jié)果如下

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

urljoin

這個(gè)的功能其實(shí)是做拼接的,例子如下:

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

結(jié)果為:

http://www.baidu.com/FAQ.html
https://pythonsite.com/FAQ.html
https://pythonsite.com/FAQ.html
https://pythonsite.com/FAQ.html?question=2
https://pythonsite.com/index.php
http://www.baidu.com?category=2#comment
www.baidu.com?category=2#comment
www.baidu.com?category=2

從拼接的結(jié)果我們可以看出,拼接的時(shí)候后面的優(yōu)先級(jí)高于前面的url

urlencode

這個(gè)方法可以將字典轉(zhuǎn)換為url參數(shù),例子如下

from urllib.parse import urlencode

params = {
    "name":"zhaofan",
    "age":23,
}
base_url = "http://www.baidu.com?"

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

結(jié)果為:

http://www.baidu.com?name=zhaofan&age=23
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Python爬蟲(chóng)入門(mén)(urllib+Beautifulsoup) 本文包括:1、爬蟲(chóng)簡(jiǎn)單介紹2、爬蟲(chóng)架構(gòu)三大模塊3...
    廖少少閱讀 10,083評(píng)論 0 6
  • 前言: 什么是cookie? Cookie,指某些網(wǎng)站為了辨別用戶身份、進(jìn)行session跟蹤而儲(chǔ)存在用戶本地終端...
    小喜_ww閱讀 2,213評(píng)論 0 7
  • 1. 網(wǎng)頁(yè)抓取 所謂網(wǎng)頁(yè)抓取,就是把URL地址中指定的網(wǎng)絡(luò)資源從網(wǎng)絡(luò)流中抓取出來(lái)。在Python中有很多庫(kù)可以用來(lái)...
    rhlp閱讀 1,138評(píng)論 0 0
  • 這是我30號(hào)在上海的見(jiàn)聞,也是我在上海的最后一天關(guān)鍵字:城隍廟,豫園,上海杜莎夫人蠟像館,上海中心大廈 上海城隍廟...
    赤樂(lè)君閱讀 783評(píng)論 0 0
  • 人怯秋寒夢(mèng)不成,中宵獨(dú)守享孤清。 霜侵石砌蟲(chóng)如訴,風(fēng)卷林梢鴉暗驚。 鐘擺勻敲人鬢影,湘簾虛度雨窗聲。 瀟瀟一夜聽(tīng)難...
    君懷璧閱讀 1,752評(píng)論 32 55

友情鏈接更多精彩內(nèi)容