我使用的是macPro , mac 自帶了python2.7 , 我自己下載了pytho3.6根據操作進行安裝后,終端默認的還是 python 2.7, 需要修改為 Python3.6
進入 ~/.bash_profile 文件,添加別名這樣默認使用的就是3.6了
alias python="/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6"
接下來就直接上代碼了
````
import urllib
import urllib.request
import re
import ssl
def getHtml(url):
# 全局取消 ssl 驗證
????ssl._create_default_https_context = ssl._create_unverified_context
????page = urllib.request.urlopen(url)
????html = page.read()#讀取URL上的數據
????returnhtml
def getImg(html):
????reg = r'src="(.+?\.jpg)" pic_ext'? #? 獲取.jpg 圖片的正則表達式
????# reg = r'src="(.+?\.jpg)"'
????imgre = re.compile(reg)# 把正則表達式編譯成一個正則表達式對象
????html = html.decode('utf-8')# python3 需要將 html 進行utf-8編碼
????imglist = re.findall(imgre,html)# 讀取html 中包含 imgre(正則表達式)的數據????
????print(imglist)
????x =0
????for imgurl in imglist:
????urllib.request.urlretrieve(imgurl,'./resource/%s.jpg'% x)# 直接將遠程數據下載到本地。第二個參數為存放的具體路徑, 如果沒有寫路徑則默認為當前文件夾下
????x +=1
????return imglist
html = getHtml('http://tieba.baidu.com/p/2460150866')
# html = getHtml('http://www.sj33.cn/dphoto/stsy/200908/20652_4.html')
print(getImg(html))
````
這里說明一下:
當使用爬取 http://tieba.baidu.com/p/2460150866網頁中的.jpg? 圖片的時候? 其正則表達是 reg = r'src="(.+?\.jpg)" pic_ext'? 不加 pic_ext? 就不能獲取到正確的數據, 即當reg = r'src="(.+?\.jpg)"'提示如下
但是使用reg = r'src="(.+?\.jpg)" pic_ext' 就能正確拿到數據.
我查看網頁源碼,在圖片鏈接后面緊跟著 pic_ext="bmp"
當使用爬取 http://www.sj33.cn/dphoto/stsy/200908/20652_4.html網頁中的.jpg? 圖片的時候? 其正則表達是 reg = r'src="(.+?\.jpg)"'? 不加pic_ext? 就獲取到正確的數據
其網頁源碼如下
按理說我的正則匹配只要匹配 以.jpg 結尾的字符串就可以了,但是現在我就有點想不明白了 為什么 http://tieba.baidu.com/p/2460150866 這個網頁的正則一定要添加'pic_ext'才能拿到數據,?reg = r'src="(.+?\.jpg)" pic_ext', ?這是什么原理?
希望知道的小伙伴解惑.