【python 3.6】从网站抓图并存放到本地路径

摘要:
.jpg格式http://t.zoukankan.com/(.+?.jpg)“'3.创建文件夹时,需要确定当前路径中是否有文件夹。可以使用两种方法,ifnot或tryexcept
#!/usr/bin/python
# -*- coding: UTF-8 -*-
_author_ = 'BH8ANK'

import urllib.request
import re
import os
import time

#os.rmdir("D:/images")

#1,打开页面,读取图片张数,抓html
wangzhi = "https://www.zhihu.com/question/43551423"
keywords = ".jpg"

def get_html(url):
    page = urllib.request.urlopen(url)
    html = page.read()
    return html

content = str(get_html(wangzhi))
a = content.count(keywords)

#print(content)
#print("此页面有%d张图" %a)

#2,匹配图片文件,抓jpg
def get_image(html):
    t = r'src="http://t.zoukankan.com/(.+?.jpg)"' #正则表达式,匹配的是r后面的内容,这部分内容来自于网页的html
    img = re.compile(t)#将正则表达式翻译成它的对象
    html1 = html.decode('utf-8')
    # html用decode('utf-8')进行解码,由bytes变成string。
    # py3的urlopen返回的不是string是bytes,如果没有这一步,就会报下面的错
    #    return _compile(pattern, flags).findall(string)
    #TypeError: cannot use a string pattern on a bytes-like object

    img_list = re.findall(img,html1)#在html中找到所有符合正则表达式的图片,存入列表list
    # try:                           #要么用异常处理方式,要么用if not判断路径是否存在
    #     os.mkdir("D:/images")
    # except FileExistsError:
    #     pass
    if not os.path.exists("D:/images"):#不存在即创建
        os.mkdir("D:/images")
    print("

Creat Success
")
    # input()
    n = 1                              #此处要重点理解的是循环变量n,这个n一边控制循环,一边给抓到的图命名
    for html in img_list:
        urllib.request.urlretrieve(html, 'D:/images/%s.jpg' %n)
        print("抓到第%3d张图"  %n,end="") #如果写为%03d,则不满3位,前面加0,如果写为%3d,则右对齐,前面不加0
        '''
        上面print中用到了end='',表示后面的打印不换行
        下面的模块负责显示抓到第几张图片时,打印进度条
        '''
        N=0.05#每隔0.05秒打印一个=
        k=1#循环控制变量,一共打印20个=,最后打印Done
        while k < 20:
            print("=", end='', flush=True)
            time.sleep(N)
            k += 1
        print("Done")
        n += 1
    print("
一共抓到%d张图"   %(n - 1))
    return img_list
    # for img_url in img_list:
    #     urllib.urlretrieve(img_url, 'D:/tmp/%s.jpg' % n)
    #     return img_list
# c = get_image(get_html(wangzhi))
# d = c.decode('utf-8')
#
# print(d)

if __name__ == "__main__":
    daima = get_html(wangzhi)
    print(daima)#此为目标网页的html代码
# input()
    get_image(daima)#从html中取出匹配的图片,并存放

代码部分本身比较简单,重点需要理解的部分是re.compile和re.findall.

容易出错的地方:

1,下面两行,为什么要decode呢

    html1 = html.decode('utf-8')
    img_list = re.findall(img,html1)

如果不decode,就会报错

【python 3.6】从网站抓图并存放到本地路径第1张

原因是:

TypeError: can't use a string pattern on a bytes-like object.

html用decode('utf-8')进行解码,由bytes变成string。

py3的urlopen返回的不是string是bytes,这一点和py2有差异。

2,下面这句的意思是筛选 【src="http://t.zoukankan.com/(.+?.jpg)"】,这部分内容是通过查看网页html来确定的

  t = r'src="http://t.zoukankan.com/(.+?.jpg)"' 

3,创建文件夹时,需要判断当前路径下,是否有这个文件夹,可以采用两种方式,if not 或者try except

免责声明:文章转载自《【python 3.6】从网站抓图并存放到本地路径》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇RPC服务和HTTP服务对比微信公众平台开发(75) 语音识别下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

将json文件转换成insert语句的sql文件

引入是要的maven依赖: 1 <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> 2 <dependency> 3 <groupId>com.google.code.gson</groupId> 4 &l...

(一)Python入门-3序列:16字典-表格数据存储-列表和字典综合嵌套

表格数据使用列表和字典存储,并实现访问   【操作】源代码(mypy08.py): 1 #使用字典存储每行记录 2 r1 = {'name':'高小一','age':18,'salary':30000,'city':'北京'} 3 r2 = {'name':'高小二','age':19,'salary':20000,'city':'上海'} 4...

python读取pdf文件

pdfplumber简介 Pdfplumber是一个可以处理pdf格式信息的库。可以查找关于每个文本字符、矩阵、和行的详细信息,也可以对表格进行提取并进行可视化调试。 文档参考https://github.com/jsvine/pdfplumber pdfplumber安装 安装直接采用pip即可。命令行中输入 pip install pdfplumber...

Java读取Properties配置文件

1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实现了Map接口,使用键值对的形式来保存属性集。不过Properties的键和值都是字符串类型。 2.Properties中的主要方法 (1)load(InputStream inStream) 此方法可以从.properties属性文件对应的文件...

python集成安装环境——Anaconda 3.5的安装

一、下载并安装 anaconda 先到https://www.continuum.io/downloads 下载anaconda, 现在的版本有python2.7版本和python3.5版本,下载好对应版本、对应系统的anaconda,它实际上是一个sh脚本文件,大约280M左右。 本系列以windows7+python3.5为例,因此我们下载如下图红框里...

学习Spring Boot:(十二)Mybatis 中自定义枚举转换器

https://blog.wuwii.com/springboot-12.html 前言 在 Spring Boot 中使用 Mybatis 中遇到了字段为枚举类型,数据库存储的是枚举的值,发现它不能自动装载。 解决 内置枚举转换器 MyBatis内置了两个枚举转换器分别是:org.apache.ibatis.type.EnumTypeHandler 和 ...