爬虫简易入门代码-爬取简单网页图片

1 篇文章 0 订阅
# -*- coding: utf-8 -*-
"""
Created on Mon Jul  9 22:12:07 2018
@author: name
"""

#!/usr/bin/env Python3
# -*- encoding:utf-8 *-*
 
'''@author = 'Appleyk'  '''
'''@time   = '2017年9月23日11:42:32' '''
 
from urllib import request
import re   #使用正则表达式
 
def getResponse(url):
    #url请求对象 Request是一个类
    url_request = request.Request(url)
    #print("Request对象的方法是:",url_request.get_method())
   
    #上下文使用的对象,包含一系列方法
    #url_response = request.urlopen(url) #打开一个url或者一个Request对象
    url_response = request.urlopen(url_request)
    '''
       geturl():返回 full_url地址
         info(): 返回页面的元(Html的meta标签)信息
         <meta>:可提供有关页面的元信息(meta-information),比如针对搜索引擎和更新频度的描述和关键词。
      getcode(): 返回响应的HTTP状态代码
      100-199 用于指定客户端应相应的某些动作。
      200-299 用于表示请求成功。      ------>  200
      300-399 用于已经移动的文件并且常被包含在定位头信息中指定新的地址信息。
      400-499 用于指出客户端的错误。  ------>  404
      500-599 用于支持服务器错误。
         read(): 读取网页内容,注意解码方式(避免中文和utf-8之间转化出现乱码)
    '''
 
    return url_response   #返回这个对象
 
def getJpg(data):
    jpglist = re.findall(r'src="http.+?.jpg"',data)
    return  jpglist
def downLoad(jpgUrl,n):
    #request.urlretrieve(jpg_link, path)
    try:
        request.urlretrieve(jpgUrl,'%s.jpg'  %n)  
    except Exception as e:
        print(e)
    finally:
        print('图片%s下载操作完成' % n)
   
 
http_response = getResponse("https://www.huxiu.com/article/251582.html") #拿到http请求后的上下文对象(HTTPResponse object)
#print(http_response.read().decode('utf-8'))
data = http_response.read().decode('utf-8')
#print(data)
global n
n = 1
L = getJpg(data)
for jpginfo in L:
    print(jpginfo)
    s = re.findall(r'http.+?.jpg',jpginfo)
    downLoad(s[0],n)
    n= n +1
   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值