码迷,mamicode.com
首页 > 编程语言 > 详细

python3爬虫下载图片之常见问题

时间:2018-06-06 23:51:40      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:port   images   one   user   def   findall   obj   wal   eve   

 

刚开始学python3,百度了下python的用法,看到爬虫下载图片很好玩,于是百度各种资料学习了下,结果总是运行不成功,最后终于改好了,记录下。

from urllib import request
import urllib
import re

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

def getImg(html):
    reg = rsrc="(.+?\.jpg)"
    imgre = re.compile(reg)
    html=html.decode(utf-8)#不写此行会报错:TypeError: cannot use a string pattern on a bytes-like object
    imglist = re.findall(imgre,html)
    x = 1
    for imgurl in imglist:
        urllib.request.urlretrieve(imgurl,C:/Users/zx/Desktop/images/%s.jpg % x)
        x+=1
    return imglist

html = getHtml("http://www.win4000.com/wallpaper_2358_0_10_1.html")
print(getImg(html))

标红的是python3和python2的不同之处,如不写则会报错:AttributeError: module ‘urllib‘ has no attribute ‘urlopen‘

如果返回[ ],可能是正则表达式不对

python3爬虫下载图片之常见问题

标签:port   images   one   user   def   findall   obj   wal   eve   

原文地址:https://www.cnblogs.com/chengyuyu/p/9147730.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!