欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python项目实战:用最简单的办法爬取最好看的图片

程序员文章站 2022-05-30 16:29:21
...

前言

接下来我们一个很基本的BeautifulSoup爬虫库来写一下爬取图片的过程,下载并存储图片,相信大家都能够看得懂的

不多说法废话了,直接上代码了

首先导入库


import urllib.requestfrom bs4 import BeautifulSoupimport os

解析网站

url = 'http://www.8she.com/31988.html'res = urllib.request.urlopen(url)
html = res.read().decode('utf-8')
soup = BeautifulSoup(html, 'html.parser')
result = soup.find_all(class_='aligncenter', limit=15)print(result)
links = []for content in result:
    links.append(content.get('src'))

下载并存储图片


if not os.path.exists('D:\\rieuse\爬虫图片\photo2'):#如果路径不存在则创建
    os.makedirs('D:\\rieuse\爬虫图片\photo2')
i = 0for link in links:
    i += 1
    filename = 'D:\\rieuse\爬虫图片\photo2\\' + 'photo' + str(i) + '.jpg'
    with open(filename, 'w') as file:
        urllib.request.urlretrieve(link, filename)
priint('下载图片:',str(i))

哈哈,是不是很简单的一个爬取图片的过程呀?欢迎大家交流,一起学习,一起报错,共同进步

点击链接加入:https://jq.qq.com/?_wv=1027&k=5ldHJHd


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69912078/viewspace-2639118/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/69912078/viewspace-2639118/