Python3簡單爬蟲抓取網頁圖片


現在網上有很多python2寫的爬蟲抓取網頁圖片的實例,但不適用新手(新手都使用python3環境,不兼容python2),
所以我用Python3的語法寫了一個簡單抓取網頁圖片的實例,希望能夠幫助到大家,並希望大家批評指正。
import urllib.request
import re
import os
import urllib
#根據給定的網址來獲取網頁詳細信息,得到的html就是網頁的源代碼  
def getHtml(url):
    page = urllib.request.urlopen(url)
    html = page.read()
    return html.decode('UTF-8')

def getImg(html):
    reg = r'src="(.+?\.jpg)" pic_ext'
    imgre = re.compile(reg)
    imglist = imgre.findall(html)#表示在整個網頁中過濾出所有圖片的地址,放在imglist中
    x = 0
    path = 'D:\\test'  
   # 將圖片保存到D:\\test文件夾中,如果沒有test文件夾則創建
    if not os.path.isdir(path):  
        os.makedirs(path)  
    paths = path+'\\'      #保存在test路徑下  

    for imgurl in imglist:  
        urllib.request.urlretrieve(imgurl,'{0}{1}.jpg'.format(paths,x))  #打開imglist中保存的圖片網址,並下載圖片保存在本地,format格式化字符串 
        x = x + 1  
    return imglist
html = getHtml("http://tieba.baidu.com/p/2460150866")#獲取該網址網頁詳細信息,得到的html就是網頁的源代碼  
print (getImg(html)) #從網頁源代碼中分析並下載保存圖片

完美

 

參考:http://www.cnblogs.com/smq772340208/p/6927063.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM