基本庫的使用

第三章、基本庫的使用
3.1 使用urllib
urllib是python內置的HTTP請求庫,也就是不需要額外安裝即可使用,它包含4個模塊。

  • request:模擬發送請求
  • error
  • parse:提供許多URL處理方法,比如拆分、解析、合併等
  • robotparser:主要是用來識別網站的robots.txt文件,判斷哪些網站可以爬

3.1.1 發送請求
1.urlopen()(urllib中的方法)

import urllib.request
response=urllib.request.urlopen('https://www.baidu.com')
print(response.read().decode('utf-8')) #返回網頁內容。去掉decode('utf-8')未出現亂碼,但有很多\n或\r\n\t,且前面有b'內部爲網頁源代碼'

通過print(type(response)),得到它是HTTPResponse類型的對象,主要包括read()、readinto()、getheaders()、getheader(name)等方法,和msg、status、closed等屬性。把它賦值爲response變量後,就可以調用這些方法和屬性

import urllib.request
response=urllib.request.urlopen('https://python.org')
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))

運行結果

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', '48747'), ('Accept-Ranges', 'bytes'), ('Date', 'Mon, 04 Jun 2018 12:14:17 GMT'), ('Via', '1.1 varnish'), ('Age', '2309'), ('Connection', 'close'), ('X-Served-By', 'cache-iad2126-IAD, cache-hnd18722-HND'), ('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '48, 82'), ('X-Timer', 'S1528114457.193407,VS0,VE1'), ('Vary', 'Cookie'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
nginx

如果想給鏈接傳遞一些參數,該怎麼實現?看一下urlopen()函數的API:

urllib.request.urlopen(url,data=None,[timeout,]*,cafile=none。。。。)

下面詳細介紹這幾個參數

  • data參數
    該參數可選,如果要添加該參數,並且如果它是字節流編碼格式的內容,即bytes類型,則需要通過bytes()方法轉化。如果傳遞了這個參數,它的請求方式就不再是GET方式,而是POST方式。
import urllib.parse
import urllib.request
data =bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf8') #urlencode()將參數字典轉化爲字符串
response=urllib.request.urlopen('https://httpbin.org/post',data=data)
print(response.read()) #加decode('utf-8')代碼變規範

運行結果

b'{"args":{},"data":"","files":{},"form":{"word":"hello"},"headers":{"Accept-Encoding":"identity","Connection":"close","Content-Length":"10","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"Python-urllib/3.6"},"json":null,"origin":"119.39.127.110","url":"https://httpbin.org/post"}\n'

httpbin.org可以提供HTTP請求測試,其中form字段的值爲data中的數據

  • timeout參數
    如果不使用該參數就會使用全局默認時間。可以通過設置這個超時時間來控制一個網頁如果長時間沒有響應,就跳過它的抓取,利用try except語句實現,代碼如下:
import socket
import urllib.request
import urllib.error
try:
    response=urllib.request.urlopen('https://httpbin.org/get',timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout): #socket.timeout類型就是超時異常,判斷e.reason是否是socket.timeout類型的錯誤,isinstance考慮繼承,type不考慮繼承
        print('TIME OUT')

2.Request(urllib中的類)
如果請求中需要加入Headers等信息,就需要更強大的Request類來構建
明天寫。。。。

發佈了32 篇原創文章 · 獲贊 12 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章