python3.4爬虫demo

yipeiwu_com5年前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 爬取古诗文存入mysql数据库的方法

使用正则提取数据,请求库requests,看代码,在存入数据库时,报错ERROR 1054 (42S22): Unknown column ‘title' in ‘field list'...

python爬取淘宝商品详情页数据

python爬取淘宝商品详情页数据

在讲爬取淘宝详情页数据之前,先来介绍一款 Chrome 插件:Toggle JavaScript (它可以选择让网页是否显示 js 动态加载的内容),如下图所示: 当这个插件处于关闭状...

itchat和matplotlib的结合使用爬取微信信息的实例

itchat和matplotlib的结合使用爬取微信信息的实例

前几天无意中看到了一片文章,《用 Python 爬了爬自己的微信朋友(实例讲解)》,这篇文章写的是使用python中的itchat爬取微信中朋友的信息,其中信息包括,昵称、性别、地理位置...

如何准确判断请求是搜索引擎爬虫(蜘蛛)发出的请求

如何准确判断请求是搜索引擎爬虫(蜘蛛)发出的请求

网站经常会被各种爬虫光顾,有的是搜索引擎爬虫,有的不是,通常情况下这些爬虫都有UserAgent,而我们知道UserAgent是可以伪装的,UserAgent的本质是Http请求头中的一...

python抓取网页图片示例(python爬虫)

复制代码 代码如下:#-*- encoding: utf-8 -*-'''Created on 2014-4-24 @author: Leon Wong''' import urllib...