码迷,mamicode.com
首页 > 编程语言 > 详细

Python爬虫学习(1)

时间:2018-01-28 11:24:56      阅读:87      评论:0      收藏:0      [点我收藏+]

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

  

Python爬虫学习(1)

标签:highlight   odi   findall   +=   lib   新建   正则   exists   post   

原文地址:https://www.cnblogs.com/MrGaoyi/p/8368384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!