urllib庫詳解

該文本是聽過崔慶才老師講解之後做的筆記。urllib有以下幾個大的功能:

目錄

urllib.request

urllib.parse

urllib.error

urllib.robotparser

urllib.cookie


urllib.request

 

import urllib.request
import urllib.parse
#response = urllib.request.urlopen('http://www.baidu.com')
#print(response.read().decode('utf8'))

 這是最簡單的爬取代碼,response返回的是byte型的,需要解碼爲unicode。

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

這個主要是來看timeout,如果在0.1秒內沒有返回任何結果,則返回錯誤。

import urllib.request
response = urllib.request.urlopen('https://www.python.org')
print(type(response))
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))
'''<class 'http.client.HTTPResponse'>
200
[('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'),
 ('X-Frame-Options', 'SAMEORIGIN'), ('x-xss-protection', '1; mode=block'),
  ('X-Clacks-Overhead', 'GNU Terry Pratchett'), ('Via', '1.1 varnish'),
   ('Content-Length', '50069'), ('Accept-Ranges', 'bytes'),
    ('Date', 'Tue, 27 Nov 2018 13:35:20 GMT'), ('Via', '1.1 varnish'),
     ('Age', '2976'), ('Connection', 'close'),
      ('X-Served-By', 'cache-iad2143-IAD, cache-tyo19932-TYO'),
       ('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '1, 3412'),
        ('X-Timer', 'S1543325721.735388,VS0,VE0'), ('Vary', 'Cookie'),
         ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
nginx'''

 response有幾個屬性,如上圖所示。

 

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': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, headers=headers, method='POST')
print(req)
response = request.urlopen(req)
print(response.read().decode('utf-8'))
'''<urllib.request.Request object at 0x000002E31B1E2588>
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "name": "Germey"
  }, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Connection": "close", 
    "Content-Length": "11", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"
  }, 
  "json": null, 
  "origin": "106.47.92.40", 
  "url": "http://httpbin.org/post"
}
'''

這個涉及到了request的使用,在下一張會詳解,記住就可以了。 

urllib.parse

from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result)
'''<class 'urllib.parse.ParseResult'> 
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')'''

 urlparse解析將一段url解析爲幾段。

from urllib.parse import urlunparse

data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data))
'''http://www.baidu.com/index.html;user?a=6#comment'''

 這個是urlunparse,將一對零散的組合成一個完整的url。

from urllib.parse import urlparse

result = urlparse('mp.csdn.net/postedit/84573678', scheme='https')
print(result)
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments=False)
print(result)
'''ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5#comment', fragment='')'''
from urllib.parse import urljoin

print(urljoin('http://www.baidu.com', 'FAQ.html'))
print(urljoin('http://www.baidu.com', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html?question=2'))
print(urljoin('http://www.baidu.com?wd=abc', 'https://cuiqingcai.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'))
'''http://www.baidu.com/FAQ.html
https://cuiqingcai.com/FAQ.html
https://cuiqingcai.com/FAQ.html
https://cuiqingcai.com/FAQ.html?question=2
https://cuiqingcai.com/index.php
http://www.baidu.com?category=2#comment
www.baidu.com?category=2#comment
www.baidu.com?category=2'''

 還有一個urljoin的用法,不過我現在覺得沒有什麼大的用處哈。

from urllib.parse import urlencode

params = {
    'name': 'germey',
    'age': 22
}
base_url = 'http://www.baidu.com?'
url = base_url + urlencode(params)
print(url)
'''http://www.baidu.com?name=germey&age=22'''

這個的用法倒是比較常見。 

urllib.error

from urllib import request, error

try:
    response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
    print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
    print(e.reason)
else:
    print('Request Successfully')
    '''Not Found
404
Server: nginx/1.10.3 (Ubuntu)
Date: Tue, 27 Nov 2018 13:56:49 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
Vary: Cookie
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Link: <https://cuiqingcai.com/wp-json/>; rel="https://api.w.org/"'''

error有幾種屬性的錯誤,常用的有HTTPError和URLError。 

urllib.robotparser

urllib.cookie

import http.cookiejar, urllib.request

cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('https://blog.csdn.net/')
for item in cookie:
    print(item.name+"="+item.value)
    '''dc_session_id=10_1543327921521.346928
uuid_tt_dd=8793671149615679850_20181127
'''

這個可以當成一個模板使用,用來獲取cookie的一些屬性。

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)

這個用來將獲取的cookie屬性保存在一個文件中,不過保存的格式是按照MozillarCookieJar來保存的。

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)

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

 這兩個是配套來使用,可以保存會話的長時間存在。注意這個是以LWPCookieJar的格式來保存的。

 

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