python-29:多級頁面爬取源碼

咱們再來看看前面說的3個步驟:html

  1. 將首頁的url傳入,經過RE將源碼中相冊的網址獲取出來
    python

  2. 將相冊的網址做爲url傳入url

  3. 經過RE獲取相冊中相片的網址
    code

代碼以下:htm

#!/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

輸出結果:
圖片

相關文章
相關標籤/搜索