Python爬虫 爬取网站上的图片

                                 Python爬虫  爬取网站上的图片

这里以这个网站为例:http://www.nipic.com/topic/show_27168_1.html

右键鼠标,查看源

然后,看到网站的源代码:

然后,发现了一些规律:图片格式大都是.jpg   ,alt 是图片的描述。 

2. 发现完这个规律那么我们就可以开始写代码啦 (用正则表达式来表示这个规律然后把网页是地址传进去就ok啦)

import urllib.request

import re

import urllib


# 根据给定的网址来获取网页详细信息,得到的html就是网页的源代码

def getHtml(url):
    page = urllib.request.urlopen(url)

    html = page.read()

    return html.decode('UTF-8')


def getImg(html):
    reg = r'src="(.+?\.jpg)" alt'

    imgre = re.compile(reg)

    imglist = imgre.findall(html)  # 表示在整个网页中过滤出所有图片的地址,放在imglist中

    x = 0

    path = 'D:\DoyoGames\python_tu\\neg' #要保存图片得路径 D:\DoyoGames\python_tu
                                            #要带后缀 \\neg
    #path = 'D:\\neg'          #保存图片放在D盘了

    # 将图片保存到D:\\test文件夹中,如果没有test文件夹则创建

    for imgurl in imglist:
        urllib.request.urlretrieve(imgurl, '{}{}.jpg'.format(path, x))  # 打开imglist中保存的图片网址,并下载图片保存在本地,format格式化字符串

        x = x + 1

    return imglist


#html = getHtml("http://www.ivsky.com/search.php?q=%E6%B5%B7&PageNo=9")  # 获取该网址网页详细信息,得到的html就是网页的源代码
#http://www.nipic.com/
html = getHtml("http://www.nipic.com/topic/show_27168_1.html")

print(getImg(html))  # 从网页源代码中分析并下载保存图片

print("爬虫成功啦,快去看看文件夹得图片")

运行结果:

保存图片的文件夹: D:\DoyoGames\python_tu (大家可以根据自己情况,修改一下

 

希望对你有帮助

猜你喜欢

转载自blog.csdn.net/qq_41204464/article/details/85346136