python-29:多级页面爬取源码

我们再来看看前面说的3个步骤:

  1. 将首页的url传入,通过RE将源码中相册的网址获取出来

  2. 将相册的网址作为url传入

  3. 通过RE获取相册中相片的网址

代码如下:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = '217小月月坑'

'''
从第一页跳转到第二页并获得图片的地址
'''

import urllib2
import re
# 极视界首页网址
url = 'http://product.yesky.com/more/506001_31372_photograph_1.shtml'
user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0'
headers = {'User-Agent':user_agent}

try:
    request = urllib2.Request(url,headers=headers)
    response = urllib2.urlopen(request)
    conents = response.read().decode("gbk")
    # 获取相册网址和相册名字
    pattern = re.compile(r'<dt><a href="(.*?)" title="(.*?)"',re.S)
    items = re.findall(pattern,conents)
    for info_url in items:
        print info_url[0],info_url[1]
        # 将相册网址传入
        info_response = urllib2.urlopen(info_url[0])
        info_conents = info_response.read().decode("gbk")
        # 获取图片网址
        info_pattern = re.compile(r'<li.*?<img src="(.*?)"',re.S)
        img_urls = re.findall(info_pattern,info_conents)
        for img_url in img_urls:
            print img_url
except urllib2.URLError,e:
    if hasattr(e,"code"):
        print e.code
    if hasattr(e,"reason"):
        e.reason

输出结果:

26133045_n8cs.jpg

 

转载于:https://my.oschina.net/u/2429887/blog/535867

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值