Python爬虫学习笔记(1):简单的图片爬取

引言:使用python编写简单的爬图片小程序


简单代码如下,要熟悉正则表达式的引用,懂得融汇贯通之后,可以爬网页上的其他内容,如新闻、评论等。

#coding=utf-8

#urllib模块提供了读取Web页面数据的接口
import urllib
#re模块主要包含了正则表达式
import re
#定义一个getHtml()函数
def getHtml(url):
    page = urllib.urlopen(url)  #urllib.urlopen()方法用于打开一个URL地址
    html = page.read() #read()方法用于读取URL上的数据
    html = html.decode('utf-8','ignore')
    return html

def getImg(html):
    a=html.split("<")
    b=""
    for i in a:
       b+=i+"\n"
    reg = r'src="(https.+?\.jpg)"'    #正则表达式,得到图片地址
    imgre = re.compile(reg)              #re.compile() 可以把正则表达式编译成一个正则表达式对象.
    imglist = re.findall(imgre,b)     #re.findall() 方法读取html 中包含 imgre(正则表达式)的数据
   
    
    #把筛选的图片地址通过for循环遍历并保存到本地
    #核心是urllib.urlretrieve()方法,直接将远程数据下载到本地,图片通过name依次递增命名
   
    name = 0
    for imgurl in imglist:
    urllib.urlretrieve(imgurl,'D:\picture\%s.jpg' % name)
            name+=1


html = getHtml("https://tieba.baidu.com/p/5089406810")
print getImg(html)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值