Python爬蟲學習(1)

來源:互聯網
上載者:User

標籤:highlight   odi   findall   +=   lib   建立   正則   exists   post   

接觸python不久,也在慕課網學習了一些python相關基礎,對於爬蟲初步認為是依靠一系列正則擷取目標內容資料

於是參照著慕課網上的教學視頻,完成了我的第一個python爬蟲,雞凍 >_<

# !/usr/bin/env python# -*- coding: UTF-8 -*-# addUser: Gao# addTime: 2018-01-27 23:06# description: python爬蟲練習import urllib2, re, os# 擷取目標網址TargetUrl = ‘https://www.imooc.com/course/list‘# 擷取資料儲存路徑FileName = ‘Download‘"""儲存圖片"""def saveImg(imgUrl, imgName=‘img.jpg‘):    # 圖片路徑    imgPath = os.path.join(FileName, imgName)    # 擷取路徑片資訊    req = urllib2.urlopen(imgUrl)    buf = req.read()    # 寫入檔案    with open(imgPath, ‘wb+‘) as f:        f.write(buf)"""判斷檔案夾是否存在"""if not os.path.exists(os.path.join(os.getcwd(), FileName)):    # 建立檔案夾    os.mkdir(os.path.join(os.getcwd(), FileName))# 擷取目標網址內容result = urllib2.urlopen(TargetUrl)urlData = result.read()# 正則匹配擷取圖片地址imgList = re.findall(r‘src="(.+?\.jpg)‘, urlData)"""迴圈儲存圖片"""i = 0for imgUrl in imgList:    saveImg(‘https:‘+imgUrl, ‘python_‘+str(i)+‘.jpg‘)    i += 1

  

Python爬蟲學習(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.