1. 程式人生 > >python 簡單的爬蟲

python 簡單的爬蟲

import urllib.request
import re
import ssl  # 處理https請求
import time
import os  # 建立目錄用


def get_html(url):
    page = urllib.request.urlopen(url)
    html = page.read()  # 返回的是 <class 'bytes'> 需要轉碼為字串型別
    html = html.decode('utf-8')  # 返回的是 <class 'str'>
    return html


reg = 'src="(.+?\.jpg)" width
' # 正則表示式 reg_img = re.compile(reg) # 編譯一下,執行更快 ssl._create_default_https_context = ssl._create_unverified_context # 因為爬蟲物件是https連結,匯入一個ssl模組就可以解決問題 imglist = reg_img.findall(get_html('http://tieba.baidu.com/p/1753935195')) # 進行匹配 def mkdir(path): # 去除首位空格 path = path.strip() # 去除尾部 \ 符號
path = path.rstrip("\\") # 判斷路徑是否存在 # 存在 True # 不存在 False isExists = os.path.exists(path) # 判斷結果 if not isExists: # 如果不存在則建立目錄 # 建立目錄操作函式 os.makedirs(path) print(path + ' 建立成功') return True else: # 如果目錄存在則不建立,並提示目錄已存在
print(path + ' 目錄已存在') return False # 定義要建立的目錄 mkpath = "picture" # 呼叫函式 picture = mkdir(mkpath) x = 0 for img in imglist: urllib.request.urlretrieve(img, mkpath+'/%s.jpg' % time.time()) x += 1 print("圖片下載完成")