温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python3.4爬虫demo

发布时间:2020-10-12 10:44:59 来源:脚本之家 阅读:134 作者:chenqiangdage 栏目:开发技术

python 3.4 所写爬虫

仅仅是个demo,以百度图片首页图片为例。能跑出图片上的图片;

使用 eclipse pydev 编写:

from SpiderSimple.HtmLHelper import *
import imp
import sys
imp.reload(sys) 
#sys.setdefaultencoding('utf-8')  
html = getHtml('http://image.baidu.com/')
try:
  getImage(html)
  exit()
except Exception as e:
  print(e) 

HtmlHelper.py文件 

上面的 SpiderSimple是自定义的包名

from urllib.request import urlopen,urlretrieve
#正则库
import re
#打开网页
def getHtml(url):
  page = urlopen(url)        
  html = page.read()
  return html
#用正则爬里面的图片地址  
def getImage(Html):
  try:
    #reg = r'src="(.+?\.jpg)" class'
    #image = re.compile(reg)  
    image = re.compile(r'<img[^>]*src[=\"\']+([^\"\']*)[\"\'][^>]*>', re.I)     
    Html = Html.decode('utf-8')
    imaglist = re.findall(image,Html)    
    x =0    
    for imagurl in imaglist:  
      #将图片一个个下载到项目所在文件夹     
      urlretrieve(imagurl, '%s.jpg' % x)
      x+=1 
  except Exception as e:
    print(e)

要注意个大问题,python 默认编码的问题。

有可能报UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128),错误。这个要设置python的默认编码为utf-8.

设置最好的方式是写bat文件,

echo off
set PYTHONIOENCODING=utf8
python -u %1

然后重启电脑。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对亿速云的支持。如果你想了解更多相关内容请查看下面相关链接

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI