Python3 爬取网页中的图片

亲测OK !

import urllib.request
import re

# 要爬取的网站
req = urllib.request.urlopen('http://www.sohu.com/a/241123779_661259')
buf = req.read()
# the type of buf : 
print (len(buf), type(buf))

# change to 
data = buf.decode('utf-8')
print (len(data), type(data))

# 正则表达式,匹配图片格式
listurl = re.findall(r'http:.+\.jpeg', data)
print (len(listurl), type(listurl))

i = 0
for url in listurl:
    # 爬取图片保存路径, 可以自己设置,这里为当前路径
    f = open(str(i) + '.jpg', "wb")
    req = urllib.request.urlopen(url)
    buf = req.read()  # 读出文件
    f.write(buf)  # 写入文件
    i = i + 1

# 显示当前路径
import os
print (os.getcwd())

你可能感兴趣的:(Python)