urllib是python的一個獲取url(Uniform Resource Locators,統一資源定址器)了,咱們能夠利用它來抓取遠程的數據進行保存哦html
urllib.request.
urlopen
(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)- url: 須要打開的網址python
- data:Post提交的數據web
- timeout:設置網站的訪問超時時間正則表達式
直接用urllib.request模塊的urlopen()獲取頁面,page的數據格式爲bytes類型,須要decode()解碼,轉換成str類型。json
from urllib import request response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse類型 page = response.read() page = page.decode('utf-8')
urlopen返回對象提供方法:瀏覽器
- read() , readline() ,readlines() , fileno() , close() :對HTTPResponse類型數據進行操做服務器
- info():返回HTTPMessage對象,表示遠程服務器返回的頭信息app
- getcode():返回Http狀態碼。若是是http請求,200請求成功完成;404網址未找到ide
- geturl():返回請求的url網站
urllib.request.
Request
(url, data=None, headers={}, method=None)使用request()來包裝請求,再經過urlopen()獲取頁面。
url = r'http://www.lagou.com/zhaopin/Python/?labelWords=label' headers = { 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3', 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label', 'Connection': 'keep-alive' } req = request.Request(url, headers=headers) page = request.urlopen(req).read() page = page.decode('utf-8')
用來包裝頭部的數據:
- User-Agent :這個頭部能夠攜帶以下幾條信息:瀏覽器名和版本號、操做系統名和版本號、默認語言
- Referer:能夠用來防止盜鏈,有一些網站圖片顯示來源http://***.com,就是檢查Referer來鑑定的
- Connection:表示鏈接狀態,記錄Session的狀態。
urllib.request.
urlopen
(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)urlopen()的data參數默認爲None,當data參數不爲空的時候,urlopen()提交方式爲Post。
from urllib import request, parse url = r'http://www.lagou.com/jobs/positionAjax.json?' headers = { 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3', 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label', 'Connection': 'keep-alive' } data = { 'first': 'true', 'pn': 1, 'kd': 'Python' } data = parse.urlencode(data).encode('utf-8') req = request.Request(url, headers=headers, data=data) page = request.urlopen(req).read() page = page.decode('utf-8')
urllib.parse.urlencode
(query, doseq=False, safe='', encoding=None, errors=None)urlencode()主要做用就是將url附上要提交的數據。
data = { 'first': 'true', 'pn': 1, 'kd': 'Python' } data = parse.urlencode(data).encode('utf-8')
通過urlencode()轉換後的data數據爲?first=true?pn=1?kd=Python,最後提交的url爲
http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python
Post的數據必須是bytes或者iterable of bytes,不能是str,所以須要進行encode()編碼
page = request.urlopen(req, data=data).read()
固然,也能夠把data的數據封裝在urlopen()參數中
def get_page(url): headers = { 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3', 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label', 'Connection': 'keep-alive' } data = { 'first': 'true', 'pn': 1, 'kd': 'Python' } data = parse.urlencode(data).encode('utf-8') req = request.Request(url, headers=headers) try: page = request.urlopen(req, data=data).read() page = page.decode('utf-8') except error.HTTPError as e: print(e.code()) print(e.read().decode('utf-8')) return page
urllib.request.
ProxyHandler
(proxies=None)當須要抓取的網站設置了訪問限制,這時就須要用到代理來抓取數據。
data = { 'first': 'true', 'pn': 1, 'kd': 'Python' } proxy = request.ProxyHandler({'http': '5.22.195.215:80'}) # 設置proxy opener = request.build_opener(proxy) # 掛載opener request.install_opener(opener) # 安裝opener data = parse.urlencode(data).encode('utf-8') page = opener.open(url, data).read() page = page.decode('utf-8') return page
# -*- coding: utf-8 -*- import urllib.request import re import os targetDir = r"D:\python\test\spider\img\douban" #文件保存路徑 def destFile(path): if not os.path.isdir(targetDir): os.mkdir(targetDir) pos = path.rindex('/') t = os.path.join(targetDir, path[pos+1:]) return t if __name__ == "__main__": #程序運行入口 weburl = "http://www.douban.com/" webheaders = { 'Connection': 'Keep-Alive', 'Accept': 'text/html, application/xhtml+xml, */*', 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko', #'Accept-Encoding': 'gzip, deflate', 'Host': 'www.douban.com', 'DNT': '1' } req = urllib.request.Request(url=weburl, headers=webheaders) #構造請求報頭 webpage = urllib.request.urlopen(req) #發送請求報頭 contentBytes = webpage.read() contentBytes = contentBytes.decode('UTF-8') for link, t in set(re.findall(r'(https:[^\s]*?(jpg|png|gif))', str(contentBytes))): #正則表達式查找全部的圖片 print(link) try: urllib.request.urlretrieve(link, destFile(link)) #下載圖片 except: print('失敗') #異常拋出
執行過程以下:
打開電腦上對應的文件夾,而後來看看圖片,這裏只是一部分哦!!。