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实现的爬取小说爬虫功能示例

本文实例讲述了Python实现的爬取小说爬虫功能。分享给大家供大家参考,具体如下: 想把顶点小说网上的一篇持续更新的小说下下来,就写了一个简单的爬虫,可以爬取爬取各个章节的内容,保存到t...

深入理解Python爬虫代理池服务

深入理解Python爬虫代理池服务

在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代理IP,从而保证爬虫快速稳定的运行,当然在公司做的东西不能开源出来。...

python3爬虫怎样构建请求header

python3爬虫怎样构建请求header

写一个爬虫首先就是学会设置请求头header,这样才可以伪装成浏览器。下面小编我就来给大家简单分析一下python3怎样构建一个爬虫的请求头header。 1、python3跟2有了细微...

Python爬虫:将headers请求头字符串转为字典的方法

原生请求头字符串 raw_headers = """Host: open.tool.hexun.com Pragma: no-cache Cache-Control: no-cach...

python爬虫入门教程之点点美女图片爬虫代码分享

继续鼓捣爬虫,今天贴出一个代码,爬取点点网「美女」标签下的图片,原图。 # -*- coding: utf-8 -*- #----------------------------...