python爬虫:从页面下载图片以及编译错误解决。

#!/usr/bin/python
import re
import urllib


def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def getImage(html):
reg = r'src="(.*?\.jpg)" title'
image = re.compile(reg)
imglist = re.findall(image,html)
x = 0
for imgurl in imglist:
urllib.urlretrieve(imgurl,'%s.jpg' % x)
x+=1


html = getHtml("http://desk.zol.com.cn/tiyu/1920x1080/")
print(getImage(html))

报错:

    “AttributeError: 'module' object has no attribute 'urlopen'”

原因是Python3里的urllib模块已经发生改变,此处的urllib都应该改成urllib.request。

#!/usr/bin/python
import re
import urllib.request


def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
return html
def getImage(html):
reg = r'src="(.*?\.jpg)" title'
image = re.compile(reg)
html = html.decode('GBK')
imglist = re.findall(image,html)
x = 0
for imgurl in imglist:
urllib.request.urlretrieve(imgurl,'%s.jpg' % x)
x+=1

html = getHtml("http://desk.zol.com.cn/tiyu/1920x1080/")
print(getImage(html))

发现读取下来后,运行到第12行,出现:

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

查找了一下,是说3.0现在的参数更改了,现在读取的是bytes-like的,但参数要求是chart-like的,找了一下,加了个编码:

html= html.decode('GBK')

#!/usr/bin/python
import re
import urllib.request

def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
return html
def getImage(html):
reg = r'src="(.*?\.jpg)" title'
image = re.compile(reg)
html = html.decode('GBK')
imglist = re.findall(image,html)
x = 0
for imgurl in imglist:
urllib.request.urlretrieve(imgurl,'%s.jpg' % x)
x+=1


html = getHtml("http://desk.zol.com.cn/tiyu/1920x1080/")
print(getImage(html))



运行成功,从页面下载图片。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值