python3.4爬虫demo

yipeiwu_com6年前Python爬虫

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

然后重启电脑。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

python使用rabbitmq实现网络爬虫示例

编写tasks.py复制代码 代码如下:from celery import Celeryfrom tornado.httpclient import HTTPClientapp = C...

python爬虫基本知识

爬虫简介       根据百度百科定义:网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照...

Python爬虫DNS解析缓存方法实例分析

本文实例讲述了Python爬虫DNS解析缓存方法。分享给大家供大家参考,具体如下: 前言: 这是Python爬虫中DNS解析缓存模块中的核心代码,是去年的代码了,现在放出来 有兴趣的可以...

python3爬虫之设计签名小程序

python3爬虫之设计签名小程序

本文实例为大家分享了python3设计签名小程序的具体代码,供大家参考,具体内容如下 首先,上一下要做的效果图: 先是这样一个丑陋的界面(我尽力了的真的!) 然后随便输入名字 然后点...

Python如何使用BeautifulSoup爬取网页信息

Python如何使用BeautifulSoup爬取网页信息

这篇文章主要介绍了Python如何使用BeautifulSoup爬取网页信息,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 简单爬取网...