python爬单页图片

任务:爬下任意贴吧某贴的单页所有图片

实现:

       我的假期任务之一就是补博客奋斗,爬单页图片是学python的第一个任务,对于大牛们来说,可能是小菜一碟,但是偶也是初学者而已,请大家见谅

       本人是龙族迷一枚,所以找了个龙族图片吧来爬

第一行必不可少 !!!  

# -*- coding: utf-8 -*

#导入模块
import urllib
import re

#定义函数,定位到我想爬的网页
def getHtml(url):
    page=urllib.urlopen(url)
    html=page.read()
    return html

#定义函数,在网页源代码里用re匹配图片格式
def getImg(html):
    reg =r'src="(.*?\.jpg)" size="'
    imgre =re.compile(reg)
    imglist=re.findall(imgre,html)
    x=0
    for imgurl in imglist:
        urllib.urlretrieve(imgurl,'%s.jpg' % x)
        x+=1
    return imglist

#将网址作为参数传入函数
html=getHtml("https://tieba.baidu.com/p/4629432244")
print getImg(html)

这样就爬下来啦

 

猜你喜欢

转载自blog.csdn.net/qq_40024605/article/details/79067319