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