1. 程式人生 > >Python爬蟲學習(1)

Python爬蟲學習(1)

數據 bin des fin load 寫入 all pytho urlopen

接觸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 = 0
for imgUrl in imgList:
    saveImg(‘https:‘+imgUrl, ‘python_‘+str(i)+‘.jpg‘)
    i += 1

  

Python爬蟲學習(1)