1. 程式人生 > >Python---對html檔案內容進行搜尋取出特定URL地址字串,儲存成列表,並使用每個url下載圖片,並儲存到硬碟上,使用正則re

Python---對html檔案內容進行搜尋取出特定URL地址字串,儲存成列表,並使用每個url下載圖片,並儲存到硬碟上,使用正則re

Python—對html檔案內容進行搜尋取出特定URL地址字串,儲存成列表,並使用每個url下載圖片,並儲存到硬碟上,正則re

對目標回包內容取出這樣類似的內容:
https://xianzhi.aliyun.com/forum/media/upload/picture/20171215230019-ab0e46aa-e1a8-1.png

2、python指令碼
在kali linux 上執行

root@kali:~/python# cat downloadxianzhi-re.py 

#coding=utf-8  
import urllib  
import re  
import sys  

def
getHtml(url):
page = urllib.urlopen(url) html = page.read() return html def getImg(html): reg = r'src="(.+?\.png)"></p>' imgre = re.compile(reg) imglist = re.findall(imgre,html) x = 0 for imgurl in imglist: urllib.urlretrieve(imgurl,'%s100.jpg'
% x) x+=1 return imglist html = getHtml("https://xianzhi.aliyun.com/forum/topic/1805/") print getImg(html)

3、執行情況
這裡寫圖片描述

這裡寫圖片描述

src="(.+?\.png)"></p>
解釋:
src="           #匹配src="
(.+?\.jpg)
# 括號表示分組,將括號的內容捕獲到分組當中
# .+表示匹配至少一個任意字元,問號?表示懶惰匹配,也就是匹配儘可能少的字串。
#  .+?\.jpg合起來表示儘可能少匹配字元的匹配到.jpg,避免匹配範圍超出src的範圍
# 這個括號也就可以匹配網頁中圖片的url了 " "></p> #匹配"></p>