Python爬蟲-爬取慕課網課程
阿新 • • 發佈:2019-01-07
Python爬取網路圖片使用正則表示式解析Html格式的檔案(其他更好的方法以後會繼續更新)
獲取慕課網課程圖片
從網站上獲取課程圖片
首先檢視頁面html程式碼
圖2 html程式碼
圖3 html程式碼
Python程式碼
環境是python3.6 IDE是pycharm
import re #正則表示式模組
from urllib import request #urllib的request模組可以非常方便地抓取URL內容
#也就是傳送一個GET請求到指定的頁面,然後返回HTTP的響應
req = request.urlopen('http://www.imooc.com/search/?words=python')
buf = req.read()
buf = buf.decode('utf-8')
listurl = re.findall(r'http:.+\.jpg', buf) #從資料中查詢http:開頭 .jpg結尾的連結
i = 0 #計數器
for url in listurl:
f = open('E:/Temp/' + str(i) + '.jpg', 'wb') #選擇儲存
req_ = request.urlopen(url) #開啟這個url(圖片連結)
buf_ = req_.read() #讀取資料到buf中
f.write(buf_) #將資料寫入檔案
i += 1
f.close()
最後在檔案目錄下可以檢視到圖片