Python简单爬虫,爬取图片

一个简单的爬虫,爬取古装美女的图片,并保存在磁盘里边

版本:py3.7.1

直接粘贴代码

# -*- coding:utf-8 -*-
import os
import requests
import re
from bs4 import BeautifulSoup
# 爬取图片的地址
url = "http://www.27270.com/zt/guzhuang/" # 古装美女
# 获取网页内容
htmls = requests.get(url).text

soup = BeautifulSoup(htmls, 'html.parser', from_encoding='utf-8')
#  findall() 全局搜索,搜索到所有img标签的元素
pic_url = soup.find_all('img', src=re.compile(r'^http://t2.hddhhn.com/uploads/tu(.*)jpg$'))

i = 0
# 判断images文件夹是否存在,如果不存在,则创建
if not os.path.exists('images'):
    os.makedirs('images')
# 利用for循环遍历图片的地址
for url in pic_url:
    img = url['src']
    try:
        pic = requests.get(img,timeout=5) # 超时异常判断 5秒超时
    except requests.exceptions.ConnectionError:
        print("图片无法下载")
        continue
    file_name = "images/"+ str(i) + ".jpg" # 存储图片的路径及保存的名字
    print(file_name)

    fp = open(file_name,'wb+')
    fp.write(pic.content) # 写入图片
    fp.close() # 关闭
    i += 1

效果如下图:

Python简单爬虫,爬取图片

Python简单爬虫,爬取图片