摘要:本文主要向大家介绍了Python语言之Python3爬虫获取,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
本文主要向大家介绍了Python语言之Python3爬虫获取,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
“AttributeError: 'module' object has no attribute 'urlopen'”
原因是Python3里的urllib模块已经发生改变,此处的urllib都应该改成urllib.request。
修改之后再运行,发现又有如下提示:
TypeError: can't use a string pattern on a bytes-like object
原因为Python3 findall数据类型用bytes类型,因此在正则表达式前应添加html = html.decode('utf-8')。
修改完后运行,成功~,不过由于网站原因,仍只能保存最近的24张背景图。最终代码如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# -*- author:arron ni-*-
# python3抓取bing主页所有背景图片
import urllib,re,sys,os
def get_bing_backphoto():
if (os.path.exists('photos')== False):
os.mkdir('photos')
for i in range(0,30):
url = '//cn.bing.com/HPImageArchive.aspx?format=js&idx='+str(i)+'&n=1&nc=1361089515117&FORM=HYLH1'
html = urllib.request.urlopen(url).read()
if html == 'null':
print( 'open & read bing error!')
sys.exit(-1)
html = html.decode('utf-8')
reg = re.compile('"url":"(.*?)","urlbase"',re.S)
text = re.findall(reg,html)
#//s.cn.bing.net/az/hprichbg/rb/LongJi_ZH-CN8658435963_1366x768.jpg
for imgurl in text :
right = imgurl.rindex('/')
name = imgurl.replace(imgurl[:right+1],'')
savepath = 'photos/'+ name
urllib.request.urlretrieve(imgurl, savepath)
print (name + ' save success!')
本文由职坐标整理并发布,希望对同学们学习Python有所帮助,更多内容请关注职坐标编程语言Python频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号